// Accounts: "Sign in with Google" and who is signed in. Using the app never
// requires an account — everything still lives in this browser (see
// persistence.ts). Signing in is for projects kept on the server and
// continued from any computer (projects.ts), PDF purchases that follow the
// person (paywall.ts), and later a page where guests find their seat. This
// file is the account itself: the header button, the dialog and the
// session; the project list inside the dialog is projects.ts's.
//
// How signing in works: Google's script renders its button in the dialog
// and, when the visitor picks an account in the popup, hands the page an ID
// token. That goes to /api/sign-in-google.php, which verifies it with
// Google, finds or creates the user and answers with a session cookie
// (httpOnly — this file never sees it). From then on /api/me.php says who
// is signed in. Google's script is loaded only when the dialog opens, so a
// visitor who never signs in never talks to Google.
//
// Without a client id for this site (sites/sites.php) the header button
// stays hidden and nothing here runs.

const GOOGLE_SIGN_IN_SCRIPT_URL = "https://accounts.google.com/gsi/client";
const GOOGLE_SIGN_IN_BUTTON_WIDTH = 272;

type AccountUser = {
  name: string;
  email: string;
  picture: string | null;
  // Everything free for this account (set by hand in the database): no PDF
  // paywall (paywall.ts) and no paid window for the guests' page (share.ts).
  freeAccess: boolean;
  // PDF download credits left on the account: every PDF purchase made
  // signed in, or claimed from the browser at sign-in, added up
  // (api/session.php). The paywall shows and spends them (paywall.ts).
  pdfDownloadsLeft: number;
};

let accountUser: AccountUser | null = null;
// The signed-in dialog has three views: the account with its project list;
// "manage account" behind a button of its own, where deleting the account
// lives — a step away from the everyday list; and the members of one
// project (projects.ts, openMembersView). Back to the first view every
// time the dialog opens.
let accountDialogView: "account" | "manage" | "members" = "account";
// The startup "who is signed in" request; the dialog waits for it so a
// signed-in browser never sees the sign-in side for a moment.
let accountUserLoaded: Promise<void> = Promise.resolve();
let googleSignInScriptLoading: Promise<void> | undefined;
// Google's library is configured once per page; only the button is redrawn.
let googleSignInInitialized = false;
let googleSignInButtonRendered = false;

const isAccountSignInAvailable = (): boolean => SITE.googleClientId !== "";

const getAccountUser = (): AccountUser | null => accountUser;

// A user as the API answers it ({name, email, picture, freeAccess,
// pdfDownloadsLeft}); null for anything else, so a changed or broken answer
// reads as "not signed in".
const readAccountUserJson = (value: unknown): AccountUser | null => {
  if (!isPlainRecord(value)) return null;
  const email = typeof value.email === "string" ? value.email : "";
  if (email === "") return null;
  const name = typeof value.name === "string" ? value.name : "";
  const picture = typeof value.picture === "string" && value.picture !== "" ? value.picture : null;
  const pdfDownloadsLeft =
    typeof value.pdfDownloadsLeft === "number" && value.pdfDownloadsLeft > 0
      ? Math.floor(value.pdfDownloadsLeft)
      : 0;
  return { name, email, picture, freeAccess: value.freeAccess === true, pdfDownloadsLeft };
};

// Bounded: the dialog waits for this answer, and a stalled request must not
// make the header button look dead for the browser's own long timeout.
const ACCOUNT_STATUS_TIMEOUT_MS = 5000;

// me.php and sign-in-google.php answer alike: the user
// (null when nobody is signed in). `reached` is false when the server could
// not be asked, or answered with an error — that is not "signed out", and
// callers that are about to charge money tell the two apart.
type AccountAnswer = { user: AccountUser | null; reached: boolean };

const readAccountAnswer = (data: unknown): AccountAnswer => {
  if (!isPlainRecord(data)) return { user: null, reached: false };
  return { user: readAccountUserJson(data.user), reached: true };
};

const fetchAccountAnswer = async (): Promise<AccountAnswer> => {
  try {
    const response = await fetch("/api/me.php", {
      cache: "no-store",
      signal: AbortSignal.timeout(ACCOUNT_STATUS_TIMEOUT_MS),
    });
    if (!response.ok) return { user: null, reached: false };
    return readAccountAnswer(await response.json());
  } catch {
    return { user: null, reached: false };
  }
};

// Asks the server again who is signed in and what the account holds, and
// applies the answer: paywall.ts does this before starting a purchase, so a
// credit bought on another computer moments ago isn't bought twice. A
// session that turns out to have ended is handled like any 401.
const refreshAccountUser = async (): Promise<AccountAnswer> => {
  const answer = await fetchAccountAnswer();
  if (!answer.reached) return answer;
  if (answer.user === null) handleAccountSessionLost();
  else setAccountUser(answer.user);
  return answer;
};

// --- Rendering ---

// The header button: "Sign in", or the signed-in person's name with their
// picture. Google's picture URLs refuse requests that carry a referrer, hence
// the no-referrer policy on the img elements in index.php.
const renderAccountHeader = () => {
  const button = document.getElementById("accountButton");
  if (!button) return;
  const text = $("#accountButtonText");
  const avatar = document.getElementById("accountAvatar") as HTMLImageElement | null;
  const icon = button.querySelector(".smallIcon") as SVGElement | null;
  const picture = accountUser?.picture ?? null;

  text.text(accountUser ? accountUser.name || accountUser.email : t("account.signIn"));
  button.title = accountUser ? accountUser.email : "";
  if (avatar) {
    if (picture !== null) avatar.src = picture;
    avatar.hidden = picture === null;
  }
  // An SVG element has no `hidden` property (that is HTMLElement's), so the
  // icon is hidden through its style.
  if (icon) icon.style.display = picture !== null ? "none" : "";
  // The settings panel: the project-file intro for the right sign-in state
  // (the file is how a signed-out visitor keeps a plan; with an account it
  // is a hand-off or an archive). "Clear everything" is for signed-out
  // visitors: with an account, a new project comes from the project list
  // and the current one stays.
  $("#projectFileIntroSignedIn").prop("hidden", accountUser === null);
  $("#projectFileIntro, #resetEverythingButton").prop("hidden", accountUser !== null);
};

const renderAccountDialog = () => {
  const signedIn = accountUser !== null;
  $("#accountSignedOut").prop("hidden", signedIn);
  $("#accountSignedIn").prop("hidden", !signedIn || accountDialogView !== "account");
  $("#accountManage").prop("hidden", !signedIn || accountDialogView !== "manage");
  $("#accountMembers").prop("hidden", !signedIn || accountDialogView !== "members");
  // Signed out with an invite link waiting (projects.ts): why to sign in.
  $("#accountJoinNote").prop("hidden", signedIn || !hasPendingJoin());
  if (!accountUser) return;
  if (accountDialogView === "members") renderMembersView();

  $("#accountManageEmail").text(accountUser.email);
  $("#accountDialogName").text(accountUser.name || accountUser.email);
  // The e-mail line is redundant when the name is missing and shown there.
  $("#accountDialogEmail")
    .text(accountUser.email)
    .prop("hidden", accountUser.name === "");
  $("#accountDialogFreeAccess").prop("hidden", !accountUser.freeAccess);
  const avatar = document.getElementById("accountDialogAvatar") as HTMLImageElement | null;
  if (avatar) {
    if (accountUser.picture !== null) avatar.src = accountUser.picture;
    avatar.hidden = accountUser.picture === null;
  }
  renderProjectsPanel();
};

// A request answered 401: the session ended elsewhere (expired, or signed
// out on another computer). The header goes back to "Sign in"; the work on
// screen stays, and signing in again resumes the same project.
const handleAccountSessionLost = () => {
  if (accountUser !== null) setAccountUser(null);
};

// Each view of the dialog has an error line; whichever is on screen shows
// the message. By id: the project list's status line shares the class when
// a save failed, and is projects.ts's to clear.
const setAccountError = (message: string | null) => {
  $("#accountError, #accountSignedInError, #accountManageError")
    .text(message ?? "")
    .prop("hidden", message === null);
};

const setAccountUser = (user: AccountUser | null) => {
  accountUser = user;
  // A session that ended (signed out elsewhere, expired) leaves the dialog
  // on its first view, so signing in again from it lands on the list.
  if (user === null) accountDialogView = "account";
  setPdfFreeAccess(user !== null && user.freeAccess);
  setPdfAccountCredits(user === null ? null : user.pdfDownloadsLeft);
  renderAccountHeader();
  renderAccountDialog();
  renderShareSection();
};

// onerror of the avatar images (index.php): Google's picture URLs rotate
// and expire, and the visitor may be offline. Rather than a broken image,
// the person is shown without a picture — the icon in the header, nothing
// in the dialog.
const handleAccountPictureError = () => {
  if (accountUser === null || accountUser.picture === null) return;
  // Only the picture: the credits the paywall shows may have moved on since
  // this user object was answered, and must not be reset from it.
  accountUser = { ...accountUser, picture: null };
  renderAccountHeader();
  renderAccountDialog();
};

// --- The dialog ---

const openAccountDialog = async () => {
  await accountUserLoaded;
  accountDialogView = "account";
  setAccountError(null);
  // (The view is set directly, not through showAccountDialogView: the
  // render below comes after the pending save and list refresh.)
  // Opening the list is a natural moment to send what is pending; before
  // the first render, so the status line tells the truth from the start
  // (the flush captures the arrangement and marks the save in flight
  // before it first awaits).
  if (accountUser !== null) {
    void flushProjectSave();
    void refreshProjectList();
  }
  renderAccountDialog();
  $("#accountDialogOverlay").removeAttr("hidden");
  if (accountUser === null) renderGoogleSignInButton();
};

const closeAccountDialog = () => {
  $("#accountDialogOverlay").attr("hidden", "hidden");
  // A note written for this opening (the sign-in's welcome) has been read.
  clearProjectsNote();
};

const isAccountDialogOpen = (): boolean => !$("#accountDialogOverlay").is("[hidden]");

// The "manage account" button and its "back" (index.php): the same dialog,
// the other view. An error from one view is not carried into the other.
const showAccountDialogView = (view: typeof accountDialogView) => {
  accountDialogView = view;
  setAccountError(null);
  renderAccountDialog();
};

// Google's script, fetched the first time the dialog opens. One attempt in
// flight at a time; a failed load can be retried by opening the dialog again.
// "Loaded" means `google` exists afterwards: content blockers often answer
// this URL with an empty 200, which fires onload all the same.
const loadGoogleSignInScript = (): Promise<void> => {
  if (typeof google !== "undefined") return Promise.resolve();
  if (googleSignInScriptLoading) return googleSignInScriptLoading;
  googleSignInScriptLoading = new Promise<void>((resolve, reject) => {
    const script = document.createElement("script");
    script.src = GOOGLE_SIGN_IN_SCRIPT_URL;
    script.async = true;
    const failed = () => {
      script.remove();
      googleSignInScriptLoading = undefined;
      reject(new Error("Google sign-in script failed to load"));
    };
    script.onload = () => {
      if (typeof google === "undefined") failed();
      else resolve();
    };
    script.onerror = failed;
    document.head.appendChild(script);
  });
  return googleSignInScriptLoading;
};

// Google draws the button itself, once; its theme is fixed at render time,
// so a theme switch clears and redraws it (see initAccount). Anything that
// goes wrong, from a blocked script to Google's code throwing, becomes the
// "could not be loaded" message rather than an empty box.
const renderGoogleSignInButton = async () => {
  const container = document.getElementById("googleSignInButton");
  if (!container || googleSignInButtonRendered) return;
  try {
    await loadGoogleSignInScript();
    // The dialog may have closed, or another call may have drawn the
    // button, while the script was loading.
    if (!isAccountDialogOpen() || googleSignInButtonRendered) return;
    if (!googleSignInInitialized) {
      google.accounts.id.initialize({
        client_id: SITE.googleClientId,
        callback: handleGoogleCredential,
        ux_mode: "popup",
        auto_select: false,
        itp_support: true,
      });
      googleSignInInitialized = true;
    }
    google.accounts.id.renderButton(container, {
      type: "standard",
      theme: document.documentElement.dataset.theme === "dark" ? "filled_black" : "outline",
      size: "large",
      text: "continue_with",
      shape: "rectangular",
      logo_alignment: "left",
      width: GOOGLE_SIGN_IN_BUTTON_WIDTH,
      locale: LANGUAGE,
    });
    googleSignInButtonRendered = true;
  } catch {
    setAccountError(t("account.googleUnavailable"));
  }
};

const clearGoogleSignInButton = () => {
  const container = document.getElementById("googleSignInButton");
  if (container) container.innerHTML = "";
  googleSignInButtonRendered = false;
};

// Google's button picked an account: the ID token goes to the server, which
// answers with the signed-in user (and sets the session cookie).
const handleGoogleCredential = async (response: google.accounts.id.CredentialResponse) => {
  setAccountError(null);
  try {
    // A PDF purchase made in this browser goes along to become the
    // account's; the answer's credits include it.
    const browserToken = getStoredPurchaseToken();
    const result = await fetch("/api/sign-in-google.php", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        credential: response.credential,
        purchaseToken: browserToken,
      }),
    });
    const { user } = readAccountAnswer(result.ok ? await result.json() : null);
    if (user === null) {
      setAccountError(t("account.signInFailed"));
      return;
    }
    setAccountUser(user);
    if (browserToken !== null) releaseClaimedPurchaseToken(browserToken);
    // The work on screen becomes a saved project, or the account's latest
    // one opens (projects.ts). The dialog stays open on the account's
    // project list — the result, or the empty list's own word about it.
    await reconcileProjects(true);
    renderAccountDialog();
  } catch {
    setAccountError(t("account.signInFailed"));
  }
};

// --- Leaving the account: signing out, deleting it ---

// One of the account's own POST endpoints (sign-out, delete-account): true
// when the server said ok. Otherwise — refused, or never reached — the
// message is shown and the header stays truthful (still signed in).
const postAccountAction = async (url: string, failedMessage: string): Promise<boolean> => {
  try {
    const response = await fetch(url, { method: "POST" });
    if (response.ok) return true;
  } catch {
    // Reported below like a refusal.
  }
  setAccountError(failedMessage);
  return false;
};

// This computer forgets the account: the arrangement is cleared (it lives
// in the account, or went with it, and the computer may be shared —
// projects.ts reloads into the pristine app), and so is the PDF purchase
// token, which was claimed by the account: the next person on this
// computer must not download on its credits.
const forgetAccountOnThisComputer = () => {
  if (typeof google !== "undefined") google.accounts.id.disableAutoSelect();
  accountUser = null;
  forgetStoredPurchaseToken();
  onAccountSignedOut();
};

// The dialog's sign-out button. Pending edits go to the account first; then
// the server forgets this browser's session.
const signOutAccount = async () => {
  setAccountError(null);
  await flushProjectSave();
  if (hasUnsavedRefusedPlan()) {
    showUnsavedPlanDialog();
    return;
  }
  if (!(await postAccountAction("/api/sign-out.php", t("account.signOutFailed")))) return;
  forgetAccountOnThisComputer();
};

// Signing out or deleting the account clears this browser — which holds the
// only copy of a plan the account refused (full, or too large; projects.ts).
// Neither goes ahead while that is so.
const showUnsavedPlanDialog = () => {
  showAlertDialog({
    title: t("account.unsavedPlanTitle"),
    description: t("account.unsavedPlanDescription"),
  });
};

// The manage view's "delete account" button: the confirm dialog (which
// sits above this one) asks once more, and only its button deletes.
const confirmDeleteAccount = () => {
  if (hasUnsavedRefusedPlan()) {
    showUnsavedPlanDialog();
    return;
  }
  showConfirmDialog({
    title: t("account.deleteAccountTitle"),
    description: t("account.deleteAccountDescription"),
    affirmativeLabel: t("account.deleteAccountConfirm"),
    onAffirmative: () => void deleteAccount(),
    dismissLabel: t("dialog.cancel"),
  });
};

// The server deletes the account with its sessions and projects
// (api/delete-account.php). Nothing is flushed first — the projects are
// what is being deleted — and nothing may go out meanwhile either: saving
// stands still (projects.ts) until the answer, and resumes only if the
// deletion was refused.
const deleteAccount = async () => {
  setAccountError(null);
  await suspendProjectSync();
  if (!(await postAccountAction("/api/delete-account.php", t("account.deleteAccountFailed")))) {
    resumeProjectSync();
    return;
  }
  forgetAccountOnThisComputer();
};

// Called from the startup block in index.php. Shows the header button when
// this site has a Google client, and asks the server who is signed in.
//
// /app/?account (the public pages' "Sign in" button) opens the dialog once
// the server has answered: the Google button for a visitor, the project
// list for someone already signed in.
const initAccount = () => {
  const dialogRequested = takeQueryParam("account") !== null;
  if (!isAccountSignInAvailable()) return;
  const button = document.getElementById("accountButton");
  if (!button) return;
  button.hidden = false;
  renderAccountHeader();
  accountUserLoaded = fetchAccountAnswer().then(async ({ user }) => {
    if (user === null) {
      // Arrived through a project's invite link: the sign-in is what
      // joins, so it is offered at once.
      if (dialogRequested || hasPendingJoin()) void openAccountDialog();
      return;
    }
    setAccountUser(user);
    await reconcileProjects(false);
    if (dialogRequested) void openAccountDialog();
  });
  window.addEventListener("themechange", () => {
    if (!googleSignInButtonRendered) return;
    clearGoogleSignInButton();
    if (isAccountDialogOpen() && accountUser === null) renderGoogleSignInButton();
  });
};
