Skip to content

The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.

JavaScript
31.7 KB
Raw Blame
/**
 * Global app state (Svelte 5 runes).
 *
 * `caseState.current` is the open case (or null). Tools read it to know where
 * to file their outputs; one-shot mode transparently creates a scratch case
 * on first write (see ensureCase).
 */
import { api } from './api.js';
import { formatCoords as renderCoords } from './coords.js';
import { loadWidth, saveWidth, clampWidth, loadSidebarView } from './sidebar.js';
import { loadTheme, saveTheme, applyTheme } from './theme.js';
import { shouldShowUpdate } from './appUpdate.js';
import { extensionVersion, pingExtensions, extensionState } from './extBridge.js';
import { classify } from './extInstall.js';
import { loadRelationTypes } from './relations.svelte.js';
import { layerMemory } from './map/layerMemory.js';

/**
 * App-wide display preferences (Settings → General), mirrored from
 * settings.json. Presentation only — every tool keeps filing decimal degrees
 * and metres, so changing these never rewrites what's on disk.
 */
export const prefs = $state({
  coordFormat: 'dd', // 'dd' | 'dms' | 'mgrs'
  units: 'metric', // 'metric' | 'imperial'
  homeView: { lat: 43, lon: 25, zoom: 3 }, // where Satellite opens
  mapSync: true, // Satellite, Compare, Detect and Horizon share one camera
  detectView: { collapsed: false, width: 380, basemap: 'esri-world-imagery' },
  captureScaleNorth: false, // burn a scale bar and a north arrow into captures
  postMention: '@GeoConfirmed', // handle a fresh post draft is addressed to
  postTarget: 'x', // social composer a fresh post draft starts with
  postTemplate: '', // id of the post template a fresh draft starts with; '' = classic
  postPrefill: true, // let the capture extension fill that composer on Publish
  reversePrefill: true, // let it hand the image to the engine on Reverse Search
  signatureHandle: '', // account handle stamped onto proofs that opt into it
  updateCheckOnStart: true, // ask GitHub for a newer release when the page loads
  updateDismissedVersion: '', // the release tag muted with "don't show again"
  tour: '', // the first-run tour: '' never started, the page it resumes on, or 'done'
  whatsNewSeen: '', // the version whose What's new was put away for good
  findBetaSeen: false, // Horizon Find's beta notice was read
  quality3d: 'full', // how much the 3D views draw on this computer (lib/quality3d.js)
});

/** The app itself, as GET /api/settings describes it: the version the welcome names. */
export const appInfo = $state({ version: '' });

/**
 * The startup update pop-up (App.svelte). `show` is flipped on once a check
 * comes back with a newer, non-muted release; the modal reads the rest.
 */
export const updateState = $state({
  show: false,
  latest: '', // the newer release tag, e.g. "v0.2.0"
  url: '', // where to download it
  notes: '', // the release body, Markdown
});

/**
 * What the startup checks found behind, feeding the dots on the Settings icon,
 * on its tabs and on the buttons that do something about it (lib/staleness.js).
 *
 * Filled once, on load — nothing here polls. Settings writes back to it when a
 * manual check or an update changes the answer, so clearing a badge doesn't
 * wait for a reload.
 */
export const updatesState = $state({
  app: null, // the /api/settings/update?check=true payload, or null
  scrapers: null, // checked downloader entries, or null while never checked
  extensionInstalled: null, // version stamped on <html> by the installed extension
  extensionBundled: '', // version this build ships (GET /api/settings)
  // The full extension verdict once the probes answer (lib/extInstall.js): which
  // copy is loaded, whether the app owns it, whether its digest is behind. The
  // two fields above are the synchronous half, and stay the fallback until this
  // arrives — a marker read costs nothing, a probe costs a timeout.
  extension: null,
});

/** Render a lat/lon the way the user asked for it. The tools' one entry point. */
export function fmtCoords(lat, lon) {
  return renderCoords(lat, lon, prefs.coordFormat);
}

// Tools mount before initSession's fetch comes back (a deep link straight to
// #satellite mounts the map on the app's first frame), so anything reading a
// preference *once* at startup — the Satellite home view — must await this
// instead of racing it. Resolves even if the settings read fails: the built-in
// defaults are a fine answer, a tool hanging forever is not.
let markPrefsReady;
export const prefsReady = new Promise((resolve) => {
  markPrefsReady = resolve;
});

export async function loadPrefs() {
  try {
    applyPrefs(await api.get('/api/settings'));
  } finally {
    markPrefsReady();
  }
}

/** Adopt a settings payload (GET /api/settings or PUT /api/settings/prefs). */
export function applyPrefs(s) {
  if (s.coord_format) prefs.coordFormat = s.coord_format;
  if (s.units) prefs.units = s.units;
  if (s.home_view) prefs.homeView = s.home_view;
  if (s.map_sync !== undefined) prefs.mapSync = s.map_sync;
  if (s.detect_view) prefs.detectView = s.detect_view;
  if (s.capture_scale_north !== undefined) prefs.captureScaleNorth = s.capture_scale_north;
  if (s.post_mention !== undefined) prefs.postMention = s.post_mention; // '' = none
  if (s.post_target !== undefined) prefs.postTarget = s.post_target;
  if (s.post_template !== undefined) prefs.postTemplate = s.post_template; // '' = none
  if (s.post_prefill !== undefined) prefs.postPrefill = s.post_prefill;
  if (s.reverse_prefill !== undefined) prefs.reversePrefill = s.reverse_prefill;
  if (s.signature_handle !== undefined) prefs.signatureHandle = s.signature_handle; // '' = none
  if (s.update_check_on_start !== undefined) prefs.updateCheckOnStart = s.update_check_on_start;
  if (s.update_dismissed_version !== undefined)
    prefs.updateDismissedVersion = s.update_dismissed_version;
  if (s.tour !== undefined) prefs.tour = s.tour;
  if (s.whats_new_seen !== undefined) prefs.whatsNewSeen = s.whats_new_seen;
  if (s.find_beta_seen !== undefined) prefs.findBetaSeen = s.find_beta_seen;
  if (s.quality_3d !== undefined) prefs.quality3d = s.quality_3d;
  if (s.extension_version !== undefined) updatesState.extensionBundled = s.extension_version;
  if (s.version) appInfo.version = s.version;
}

/**
 * On page load, work out what is behind: a newer Azimut release, a newer
 * downloader, a newer capture extension. Runs once — nothing here polls, and
 * nothing re-checks when Settings opens.
 *
 * The extension half is a local comparison (the installed one stamps its
 * version on <html> at document_start), so it happens either way. The two
 * network calls are gated together on `updateCheckOnStart`: with it off,
 * opening the app still phones nowhere. Never throws — offline is the normal
 * case here, and a check that fails just leaves the badge unlit.
 */
export async function checkForUpdatesOnStart() {
  updatesState.extensionInstalled = extensionVersion();
  // Deliberately before the gate and deliberately not awaited: reading the app's
  // own folder and asking the bridges who they are touches no network, so it runs
  // even with the release check switched off, and nothing else waits on it.
  checkExtension();
  if (!prefs.updateCheckOnStart) return;
  const [app, scrapers] = await Promise.allSettled([
    api.get('/api/settings/update?check=true'),
    api.get('/api/settings/scrapers?check=true'),
  ]);
  if (app.status === 'fulfilled') {
    updatesState.app = app.value;
    if (shouldShowUpdate(app.value, prefs.updateDismissedVersion)) {
      updateState.latest = app.value.latest;
      updateState.url = app.value.url;
      updateState.notes = app.value.notes ?? '';
      updateState.show = true;
    }
  }
  if (scrapers.status === 'fulfilled') updatesState.scrapers = scrapers.value.scrapers ?? [];
}

/**
 * What this browser runs against what the app ships: one local read and the two
 * bridge probes, reconciled by `classify`.
 *
 * This is what lets the badge see a digest move. The version comparison it falls
 * back on cannot: a release that leaves the extension alone keeps its version,
 * and within a development cycle the bundled version is already the app's own —
 * so "behind" and "identical" look the same from a version alone.
 *
 * Never throws. A failure leaves `extension` null and the version fallback in
 * charge, which is where the badge was before this existed.
 */
export async function checkExtension() {
  try {
    const [server, bridges, managed] = await Promise.all([
      api.get('/api/settings/extension'),
      pingExtensions(),
      extensionState(),
    ]);
    updatesState.extension = classify(server, { bridges, managed });
  } catch {
    /* the fallback is the badge's previous behaviour, which is a fine answer */
  }
  return updatesState.extension;
}

/** Close the update pop-up. `mute` remembers the tag so it won't show again. */
export async function dismissUpdate(mute = false) {
  updateState.show = false;
  if (mute && updateState.latest) {
    try {
      applyPrefs(await api.put('/api/settings/prefs', { update_dismissed_version: updateState.latest }));
    } catch {
      /* the mute is a nicety; failing to persist it just means it re-shows */
    }
  }
}

/**
 * Keep where the tour stands, which What's new was read and whether Find's beta
 * notice was (lib/onboarding.js): `{ tour, whats_new_seen, find_beta_seen }`, any of
 * them. Taken at once, so the next page never waits on the disk.
 */
export async function keepOnboarding(fields) {
  if (fields.tour !== undefined) prefs.tour = fields.tour;
  if (fields.whats_new_seen !== undefined) prefs.whatsNewSeen = fields.whats_new_seen;
  if (fields.find_beta_seen !== undefined) prefs.findBetaSeen = fields.find_beta_seen;
  try {
    await api.put('/api/settings/prefs', fields);
  } catch {
    /* the tour then starts over, or What's new shows again: a nicety lost, not work */
  }
}

export const caseState = $state({
  current: null, // { id, name, scratch, entities, links, ... }
  list: [],
  folders: [], // workspace folders that are not cases yet: { name, state }
  loading: false,
  rev: 0, // bumped on every reload so tools can re-fetch their own artifacts
});

/**
 * Reusable house-style presets (Settings → Templates), app-wide like the
 * signature. Two families: `proof` (a proof's layout/colours/legend) and
 * `post` (a thread skeleton). Loaded once at startup and refreshed whenever
 * Settings edits one, so the composers' "start from a template" menus stay
 * current without re-fetching. Each entry: { id, name, updated_at, data }.
 */
export const templatesState = $state({ proof: [], post: [], map: [] });

/**
 * The Post composer's live draft, mirrored for the template editor's preview so
 * a layout can be judged on the post that is open. Content only: the values the
 * tokens stand for, or `null` while the composer holds nothing.
 */
export const postDraftState = $state({ fields: null });

export async function loadTemplates() {
  try {
    const t = await api.get('/api/templates');
    templatesState.proof = Array.isArray(t.proof) ? t.proof : [];
    templatesState.post = Array.isArray(t.post) ? t.post : [];
    templatesState.map = Array.isArray(t.map) ? t.map : [];
  } catch {
    /* templates are a convenience; an empty store is a fine fallback */
  }
}

/** Create or update a preset (id present → update), then refresh the store. */
export async function saveTemplate(kind, { id, name, data }) {
  const rec = await api.post(`/api/templates/${kind}`, { id, name, data });
  await loadTemplates();
  return rec;
}

export async function deleteTemplate(kind, id) {
  await api.del(`/api/templates/${kind}/${id}`);
  await loadTemplates();
}

export const uiState = $state({
  // Where the app opens (lib/workspaces.js). Home rather than a tool, because a
  // fresh install lands in a workspace with no case, and the Media Library's empty
  // state cannot say what any of the rail means. A deep link still wins.
  tool: 'overview',
  theme: loadTheme(), // 'dark' | 'light'; index.html stamps it before first paint
  sidebarOpen: true,
  sidebarW: loadWidth(), // px, drag-resizable and remembered across reloads
  sidebarView: loadSidebarView(), // 'folders' | 'todo' | 'recent', remembered across reloads
  toasts: [],
  settingsTab: null, // settings section id to open when switching to Settings
  // The guide open over the tools, and what it opened on: a tool, a page or a
  // journey (`{ at }`, lib/guide.js `landingFor`). Null while it is closed.
  guide: null,
  // The welcome, the tour or What's new over everything (components/Onboarding.svelte):
  // `{ kind, step?, pages? }` as lib/onboarding.js `onStart` gives it. Null while closed.
  onboarding: null,
  // cross-tool handoffs (the workbench glue):
  composeQueue: [], // media paths queued for the Proof Composer
  postProof: null, // proof spec handed to the Post Composer
  openProof: null, // proof name to load in the Proof Composer
  openDraft: null, // draft name to load in the Post Composer
  openNotebook: null, // { noteId: string|null }; null noteId opens case notes.md
  inspectPath: null, // media path to open in the Inspect tool
  /**
   * A picture handed to Reverse Search from wherever it is being looked at, in the
   * shape `normalizeReverseTarget` (lib/reverseSearch.js) returns: a case file by
   * its path, or a picture that exists nowhere on disk — an Inspect frame not yet
   * saved, a proof panel as cropped — as a Blob. Consumed once, session-only.
   */
  reverseTarget: null,
  focusMedia: null, // media path to highlight & scroll to in the Media Library
  openInspect: null, // name of a file's Inspect work, reopened on that file
  openCollage: null, // collage name to reopen in the Collage tool
  openCompare: null, // compare-session name to reopen in the Compare tool
  openHorizonView: null, // saved Horizon view name to reopen in the Horizon tab
  openHorizonFind: null, // a search the case keeps, to open in Horizon's Find
  openPlate: null, // map plate name to reopen in the Map plate tool
  openPlateTemplate: null, // map template id to edit in the Map plate tool, from Settings
  newPlate: false, // the Map asked for a plate of what it shows: the Map plate tool opens one
  editLayer: null, // { name, title, view }: a plate made a layer to draw in; the Map opens it for editing there
  focusMode: false, // a tool gave its page the whole window (the plate's focus): the app's bars and rail step aside
  openAnalyzer: null, // saved Detect item stem to reopen without loading imagery
  // Entity id the Board should open Details on. The graph-only types — a person,
  // an account, a claim — have no tool of their own to be reopened in, so the
  // board is where following a relation to one of them lands.
  openBoardEntity: null,
  /**
   * A question worked out in the Board, handed to the graph to be drawn.
   *
   * `{ terms, label }` — the catalog filter as request parameters, and the sentence
   * it reads as. The **filter** travels rather than the ids it matched, which is what
   * makes this work at any size: the graph asks the case the same question the table
   * asked, so nothing is capped, no URL carries five hundred ids, and the drawing
   * stays live as the case changes under it. Both surfaces resolve it through one
   * predicate, so they cannot disagree about what it means.
   */
  drawInGraph: null,
  /** One entity the graph should draw and select, wherever it came from. The mirror
   *  of `openBoardEntity`: a node has to be reachable from the row as much as a row
   *  from the node. */
  openGraphEntity: null,
  /** A sheet id the Sheet tab should open instead of its home. Consumed once. */
  openSheet: null,
  /** Entity/item handed to Timeline from Details. Timeline consumes and clears it. */
  timelineFocus: null, // { entityId, entityLabel, itemId, producedHere }
  /** A fact-time range handed back to Timeline. Consumed once, never persisted. */
  timelineRange: null, // { from, to, itemId?, item? }
  /** A holding queue the Timeline should open onto, from a count that named it. */
  timelineQueue: null, // 'undated', or { queue: 'undated' | 'unplaced', itemId, item }
  /** Whether the Add event bar is open over the tool on screen. Session only. */
  noting: false,
  /** Entities the Move to… dialog is open on, from Files, the sidebar or a toast
   *  that filed something into the work folder. Session only. */
  moving: null,
  /** Bumped to send the Timeline to its own entry line, which is the Add event bar
   *  the Timeline already has. */
  timelineLineFocus: 0,
  /** A fact-time range handed to the Satellite map as a temporary event layer. */
  mapTimelineRange: null, // { from, to }
  /**
   * A sheet's column of coordinates, handed to the map as a temporary layer.
   *
   * The **points travel**, not a query — which is the opposite of `drawInGraph` and for
   * a reason: a sheet's coordinates are text in a file, not entities the case can be
   * asked about, so there is no question the map could re-ask. Session-only, consumed
   * and cleared by Satellite, and never part of a capture or a proof.
   */
  mapSheetPoints: null, // { points: [{ lat, lon, label, decimals }], sheet, column }
  gotoCoords: null, // { lat, lon } to fly to in the Satellite tool
  // A point, a date and a time handed over by Coords & Sky: the Satellite tab
  // opens its Sun & moon mode there. Session-only, and never part of a capture
  // or a proof.
  skyAt: null, // { lat, lon, date, time }
  /**
   * Where the map is, for the tools that would otherwise open on nothing.
   *
   * The point the map records — its moved pin, else its centre — published once
   * the analyst has moved off the view the map opened at, so a fresh window
   * never offers the home view as if it were a finding. Session-only, read by
   * Coords & Sky, and never part of a capture, a proof or a case.
   */
  mapPoint: null, // { lat, lon, zoom }
  /**
   * The window's camera, which Satellite, Compare, Detect and Horizon share
   * while `prefs.mapSync` is on (`lib/map/sharedView.js`): `{ lat, lon, zoom,
   * bearing, by }`, where `by` is the tab that wrote it or 'link' for the
   * chain. Horizon writes its eye there, turned to its heading. Session-only. A case switch leaves it: a camera is not case state.
   */
  mapView: null,
  /**
   * A pair of dated views of one point, handed to Compare from the map's own
   * right-click menu: `{ lat, lon, zoom, a, b, title }`, where each side is the
   * shape `applySide` already reads off a saved comparison. The dates are
   * looked up where the menu is pressed, so Compare opens on two pictures
   * rather than on two empty panes. Consumed once, session-only.
   */
  compareAt: null,
  /**
   * A point another map tab was asked to look at, from the right-click menu's
   * Open in…: `{ tool: 'compare' | 'detect', lat, lon, zoom }`. That tab moves
   * its camera there and keeps its own pictures and work; Satellite takes the
   * same hand-off as `gotoCoords`. Consumed once, session-only.
   */
  lookAt: null,
  /**
   * An eye handed to the Horizon tab from a map's right-click, Look from here:
   * `{ lat, lon, heading? }`. Consumed once, session-only.
   */
  horizonAt: null,
  /**
   * Where the Horizon tab's eye stands and looks, once it rests: `{ lat, lon,
   * heading, fov, projection }`. Satellite draws it as a dashed cone, the view
   * no save has kept. Session-only, and not case state: a camera is not.
   */
  horizonEye: null,
  /**
   * A photo or a video handed to the Horizon tab to lay over its view, from
   * Inspect: `{ path, kind, title?, time? }`. Consumed once, session-only.
   */
  horizonPhoto: null,
  /**
   * A Horizon setting asked for from the command palette, by its id
   * (lib/horizon/panelIndex.js): the inspector opens its group and lights it.
   * Consumed once, session-only.
   */
  horizonSetting: null,
  focusCapture: null, // case-relative capture path selected from another workspace
  // Satellite reference viewers: floating scratch windows holding a media image
  // over the map to eyeball against the imagery. Session-only — never captured
  // or saved, and dropped when the open case changes (they point at its media).
  refViewers: [],
});

/** Switch light/dark, mirror it to <html>, and remember it across reloads. */
export function setTheme(theme) {
  uiState.theme = theme === 'light' ? 'light' : 'dark';
  applyTheme(uiState.theme);
  saveTheme(uiState.theme);
}

/** Flip to the other theme. Wired to the rail toggle. */
export function toggleTheme() {
  setTheme(uiState.theme === 'light' ? 'dark' : 'light');
}

/**
 * Resize the case sidebar (px). Clamped against the live window, so a width
 * dragged out on a big screen can't wedge the canvas shut on a small one.
 * Kept out of localStorage until the drag ends — see persistSidebarWidth.
 */
export function setSidebarWidth(w) {
  uiState.sidebarW = clampWidth(w, window.innerWidth);
}

/** Remember the current sidebar width for the next session. */
export function persistSidebarWidth() {
  saveWidth(uiState.sidebarW);
}

let toastSeq = 0;

/**
 * Say something at the foot of the window, for `timeout` milliseconds.
 *
 * A timeout of 0 holds it up until `dismissToast` takes it down, which is how a
 * wait of unknown length is said: the message has to outlast the work rather
 * than a guess at how long the work takes. Returns the id either way.
 *
 * Without a timeout, a failure or a toast offering an action stays long enough to
 * be read and pressed; a plain confirmation goes quickly. `error` is taken as
 * `danger`, the one kind the toast styles as a failure.
 */
export function toast(message, kind = 'info', timeout = null, action = null) {
  const id = ++toastSeq;
  if (kind === 'error') kind = 'danger';
  if (timeout == null) timeout = kind === 'danger' || action ? 8000 : 3800;
  uiState.toasts.push({ id, message, kind, action });
  if (timeout > 0) setTimeout(() => dismissToast(id), timeout);
  return id;
}

/** Take one down early, or take down one that was never given a timeout. */
export function dismissToast(id) {
  const i = uiState.toasts.findIndex((t) => t.id === id);
  if (i !== -1) uiState.toasts.splice(i, 1);
}

export async function refreshCaseList({ q } = {}) {
  const query = q?.trim();
  caseState.list = await api.get(`/api/cases${query ? `?q=${encodeURIComponent(query)}` : ''}`);
  // Folders the analyst made in the workspace and Azimut has not been told
  // about yet. Not a case list, so it takes no query; the switcher filters it.
  try {
    caseState.folders = await api.get('/api/workspace/folders');
  } catch {
    caseState.folders = []; // never keep the switcher from listing real cases
  }
}

/**
 * Make a case out of a workspace folder, in place. Nothing inside it moves:
 * the files stay in the analyst's half of the case folder.
 */
export async function adoptFolder(name) {
  if (!(await leaveCurrentCase('create'))) return null;
  const adopted = await api.post('/api/workspace/folders/adopt', { name });
  await refreshCaseList();
  await openCase(adopted.id, { asked: true });
  return adopted;
}

/** Write back the manifest of a folder holding a case that lost it. */
export async function recoverFolder(name) {
  const recovered = await api.post('/api/workspace/folders/recover', { name });
  await refreshCaseList();
  return recovered;
}

// Remember the last open case across page reloads so work is never "lost".
const LAST_CASE_KEY = 'azimut:lastCase';

function rememberCase(id) {
  try {
    if (id) localStorage.setItem(LAST_CASE_KEY, id);
    else localStorage.removeItem(LAST_CASE_KEY);
  } catch {
    /* localStorage unavailable (private mode) — non-fatal */
  }
}

let openingCase = 0;
const caseChangeGuards = new Set();

/** Finish case-owned work before another case becomes current. A guard returning
 *  false keeps the current case open, so a failed save cannot be mistaken for a
 *  successful switch. */
export function registerCaseChangeGuard(guard) {
  caseChangeGuards.add(guard);
  return () => caseChangeGuards.delete(guard);
}

async function prepareCaseChange(fromId, toId, reason = null) {
  const change = reason ? { fromId, toId, reason } : { fromId, toId };
  for (const guard of [...caseChangeGuards]) {
    if ((await guard(change)) === false) return false;
  }
  return true;
}

/**
 * Ask the guards before a server write that ends on another case: a new case, an
 * adopted folder, a promoted session. Asked after, a "Keep editing" would leave the
 * write done anyway, and a promoted session would stay open on a folder that moved.
 */
async function leaveCurrentCase(reason) {
  const fromId = caseState.current?.id ?? null;
  if (!fromId) return true;
  return (await prepareCaseChange(fromId, null, reason)) && caseState.current?.id === fromId;
}

/** Open a case. `asked` skips the guards, for a caller that already ran them.
 *  Answers whether the case is now current. */
export async function openCase(id, { asked = false } = {}) {
  const run = ++openingCase;
  caseState.loading = true;
  try {
    const currentId = caseState.current?.id ?? null;
    if (
      currentId && currentId !== id && !asked &&
      !(await prepareCaseChange(currentId, id))
    ) return false;
    if (run !== openingCase) return false;
    // Everything queued names something in the case being left behind —
    // reference viewers point at its media, `openProof` at one of its files.
    if (caseState.current?.id !== id) clearCaseHandoffs();
    const opened = await api.get(`/api/cases/${id}`);
    // Case reads can finish out of order. Only the latest choice may become current,
    // or a slow first click can put its case back after a faster second one opened.
    if (run !== openingCase) return false;
    caseState.current = opened;
    rememberCase(id);
    return true;
  } finally {
    if (run === openingCase) caseState.loading = false;
  }
}

/**
 * Startup: load the case list and reopen the last-used case (if it still
 * exists on disk). Called once from App on mount.
 */
export function initSession(explicitCaseId = null) {
  const starting = startSession(explicitCaseId);
  started = starting.catch(() => {});
  return starting;
}

let started = Promise.resolve();

/** Settled once startup has reopened its case: one opened before that would be replaced by it. */
export function sessionStarted() {
  return started;
}

async function startSession(explicitCaseId) {
  // preferences must land before the tools render, or coordinates would flash
  // in the wrong format; a settings read failure is never fatal to a session
  await loadPrefs().catch(() => {});
  await loadTemplates().catch(() => {});
  // The relation vocabulary is code, not case data, and several surfaces name an
  // edge with it on their first paint. Reading it here means no relation row ever
  // renders a type slug it would replace a moment later.
  await loadRelationTypes().catch(() => {});
  await refreshCaseList();
  const requested = typeof explicitCaseId === 'string' ? explicitCaseId.trim() : '';
  if (requested) {
    // A detached map names its owner in the URL. Falling back to shared
    // localStorage here could make the copied view write into another tab's case.
    await openCase(requested);
    return;
  }
  let lastId = null;
  try {
    lastId = localStorage.getItem(LAST_CASE_KEY);
  } catch {
    /* ignore */
  }
  if (lastId) {
    try {
      await openCase(lastId);
    } catch {
      rememberCase(null); // it was deleted — forget it
    }
  }
}

let reloadingCase = 0;

export async function reloadCase() {
  const id = caseState.current?.id;
  if (!id) return;
  const selection = openingCase;
  const run = ++reloadingCase;
  const reloaded = await api.get(`/api/cases/${id}`);
  // A write may finish while another case is being opened. Its refresh belongs to
  // the case it started in and must never put that case back under the analyst.
  if (
    run !== reloadingCase ||
    selection !== openingCase ||
    caseState.current?.id !== id
  ) return;
  caseState.current = reloaded;
  caseState.rev++;
}

/** Create a case and open it. Answers null when it is not the one now open: the analyst kept
 *  theirs, or another case was chosen while it was being made. */
export async function createCase(name) {
  if (!(await leaveCurrentCase('create'))) return null;
  const created = await api.post('/api/cases', { name });
  await refreshCaseList();
  return (await openCase(created.id, { asked: true })) ? created : null;
}

/**
 * One-shot mode: make sure some case exists to receive tool output.
 * Creates a scratch case silently if none is open (spec §3.3).
 */
export async function ensureCase() {
  if (caseState.current) return caseState.current;
  const scratch = await api.post('/api/cases/scratch');
  await refreshCaseList();
  await openCase(scratch.id);
  toast('Scratch session started. Use “Keep as case…” to save it', 'info');
  return caseState.current;
}

/**
 * Rename a case in place (keeps the same id/folder — only the display name
 * changes). Refreshes the list, and the open case if it is the one renamed.
 */
export async function renameCase(id, name) {
  await api.patch(`/api/cases/${id}`, { name });
  await refreshCaseList();
  if (caseState.current?.id === id) await openCase(id);
}

/** Keep the open scratch session as a case. Answers null when the analyst kept
 *  editing: the session is then left where it is. */
export async function promoteCase(name) {
  const scratch = caseState.current;
  if (!scratch?.scratch) return null;
  if (!(await leaveCurrentCase('promote'))) return null;
  const promoted = await api.post(`/api/cases/${scratch.id}/promote`, { name });
  await refreshCaseList();
  await openCase(promoted.id, { asked: true });
  toast(`Promoted to case “${name}”`, 'ok');
  return promoted;
}

/**
 * Drop every queued cross-tool handoff.
 *
 * A handoff names something in the case that queued it — a proof, a draft, a
 * media path, a point on the map — and the effects that consume one only check
 * that *some* case is open. So anything still queued when the open case changes
 * would be spent against the case that replaced it.
 *
 * One list, called from both `closeCase` and `openCase`. Written out twice they
 * drifted, and switching between two cases went on carrying `openProof`,
 * `openDraft`, `openInspect`, `composeQueue`, `inspectPath`, `focusMedia`,
 * `postProof`, `gotoCoords` and `skyAt` across the boundary.
 */
function clearCaseHandoffs() {
  uiState.composeQueue = [];
  uiState.postProof = null;
  uiState.openProof = null;
  uiState.openDraft = null;
  uiState.openNotebook = null;
  uiState.inspectPath = null;
  uiState.reverseTarget = null;
  uiState.focusMedia = null;
  uiState.focusCapture = null;
  uiState.openInspect = null;
  uiState.openCollage = null;
  uiState.openCompare = null;
  uiState.openHorizonView = null;
  uiState.openHorizonFind = null;
  uiState.openPlate = null;
  uiState.newPlate = false;
  uiState.openAnalyzer = null;
  uiState.drawInGraph = null;
  uiState.openBoardEntity = null;
  uiState.openGraphEntity = null;
  uiState.openSheet = null;
  uiState.timelineFocus = null;
  uiState.timelineRange = null;
  uiState.timelineQueue = null;
  uiState.noting = false;
  uiState.moving = null;
  uiState.mapTimelineRange = null;
  uiState.gotoCoords = null;
  uiState.lookAt = null;
  uiState.horizonAt = null;
  uiState.horizonPhoto = null;
  uiState.skyAt = null;
  uiState.refViewers = [];
}

/**
 * Close the open case (dropping back to one-shot mode). Also clears every
 * cross-tool handoff — see `clearCaseHandoffs`.
 */
export function closeCase() {
  // Invalidate an open or refresh still in flight before dropping the current case.
  openingCase++;
  caseState.current = null;
  rememberCase(null);
  clearCaseHandoffs();
}

/**
 * Permanently delete a case and everything it contains (the whole folder on
 * disk — media, satellite, proofs, exports). Irreversible; the caller is
 * responsible for the "type DELETE" confirmation. If the deleted case is the
 * one open, we drop back to one-shot mode.
 */
export async function deleteCase(id) {
  await api.del(`/api/cases/${id}`);
  // the layers each map had on in it, kept in this browser (lib/map/layerMemory)
  layerMemory.forget(id);
  if (caseState.current?.id === id) closeCase();
  await refreshCaseList();
}