// One confirmation prompt for the whole app, asked inside the page.
//
// window.confirm() reads like the obvious tool and is not: a browser that
// suppresses native dialogs — an embedded webview, a blocked-dialogs setting —
// never shows it and hands back false, so the action silently does not happen
// and nothing says why. That is indistinguishable from a broken button, and it
// was one: removing a home charger did nothing at all until the prompt moved
// into the page.
//
// askConfirm() renders the question as part of the page (ConfirmDialog.vue,
// mounted once in App.vue) and resolves to what the user actually pressed:
//
//   if (!(await askConfirm(t("car.parts.confirmDelete")))) return;
import { reactive } from "vue";

export const confirmPrompt = reactive({
  open: false,
  title: "",
  message: "",
  confirmLabel: "", // blank falls back to the dialog's own wording
});

let settle = null;

export function askConfirm(message, { title = "", confirmLabel = "" } = {}) {
  // Asking a second question while one is open answers the first with no.
  // Nothing in the app asks two at once, and an abandoned promise would hang
  // whoever awaited it.
  if (settle) settle(false);
  Object.assign(confirmPrompt, { open: true, title, message, confirmLabel });
  return new Promise((resolve) => {
    settle = resolve;
  });
}

// Answers the open question. Closing the dialog any other way — the backdrop,
// Cancel — is a no, never a dropped promise.
export function answerConfirm(value) {
  confirmPrompt.open = false;
  const done = settle;
  settle = null;
  if (done) done(value);
}
