Skip to content

Free & Open-Source Invoice Generator - No Sign-Up, No Ads, Instant PDF Export, 100% In-Browser, and Fully Customizable Templates.

37.0 KB
Raw Blame
"use client";

import * as Sentry from "@sentry/nextjs";
import {
  compressToEncodedURIComponent,
  decompressFromEncodedURIComponent,
} from "lz-string";
import { usePathname, useSearchParams } from "next/navigation";
import { useCallback, useEffect, useRef, useState } from "react";
import { toast } from "sonner";

import { APP_PAGE_TITLE } from "@/app/(main)/(app)/app-page-heading";
import { InvoicePageHeader } from "@/app/(main)/(app)/components/invoice-page-header";
import { InvoicePdfInstanceProvider } from "@/app/(main)/(app)/contexts/invoice-pdf-instance-context";
import { InvoicePageLoadingSkeleton } from "@/app/(main)/(app)/loading";
import { getAppStorageItem } from "@/app/(main)/(app)/utils/app-local-storage";
import {
  ensureAppMetadata,
  updateAppMetadata,
} from "@/app/(main)/(app)/utils/get-app-metadata";
import type { ChangelogSummary } from "@/app/(main)/changelog/utils";
import { getInitialInvoiceData } from "@/app/constants";
import {
  invoiceSchema,
  PDF_DATA_LOCAL_STORAGE_KEY,
  type InvoiceData,
} from "@/app/schema";
import { GitHubStarCTA } from "@/components/github-star-cta";
import { Button } from "@/components/ui/button";
import { TooltipProvider } from "@/components/ui/tooltip";
import { useDeviceContext } from "@/contexts/device-context";
import { debugLog } from "@/lib/debug-log";
import { haptic } from "@/lib/haptic";
import { umamiTrackEvent } from "@/lib/umami-analytics-track-event";
import {
  buildInvoiceAppUrl,
  getRouteTemplate,
  getTemplateFromUrl,
  isUrlForTemplate,
} from "@/utils/invoice-app-url";
import {
  compressInvoiceData,
  decompressInvoiceData,
} from "@/utils/url-compression";

import { InvoiceClientPage } from "./components";
import { ChangelogUpdatePopup } from "./components/changelog-update-popup";
import { HowItWorksVideoDialog } from "./components/how-it-works-video-dialog";
import { CANNOT_SHARE_INVOICE_DESCRIPTION } from "./components/share-invoice-button";
import { useChangelogUpdatePopup } from "./hooks/use-changelog-update-popup";
import { useInAppBrowserNotice } from "./hooks/use-in-app-browser-notice";
import { generateQrCodeDataUrl } from "./utils/generate-qr-code-data-url";
import { handleInvoiceNumberBreakingChange } from "./utils/invoice-number-breaking-change";
import { selectInvoiceTemplate } from "./utils/select-invoice-template";

// TODO: enable later when PRO version is released, this is PRO FEATURE =)
// import { InvoicePDFDownloadMultipleLanguages } from "./components/invoice-pdf-download-multiple-languages";

/**
 * Rewrites the URL of the invoice app in place.
 *
 * Every URL rewrite on this page is cosmetic -- keeping the template in sync (`/` vs
 * `/stripe-template`), adding or dropping `?data=` -- and lands on the page
 * that is already rendered. `router.replace` treats each one as a navigation and refetches
 * the RSC payload (and, for a template switch, would remount the editor on the other
 * route), so a plain page load spent a whole extra server round trip just to tidy up the
 * URL. Next's router syncs with the native History API, so
 * `usePathname()` and `useSearchParams()` still update and nothing is refetched.
 *
 * @param url - The root-relative URL to put in the address bar, see `buildInvoiceAppUrl`.
 */
function replaceUrl(url: string) {
  window.history.replaceState(null, "", url);
}

/**
 * Rewrites only the query string, keeping the current pathname (and so the template).
 *
 * @param params - The complete query string to put in the address bar.
 */
function replaceUrlQuery(params: URLSearchParams) {
  const query = params.toString();

  replaceUrl(query ? `?${query}` : window.location.pathname);
}

/**
 * Main client component for the invoice application page.
 *
 * This component handles:
 * - Loading and persisting invoice data from/to localStorage
 * - URL-based invoice sharing via compressed data in query parameters
 * - Template selection and validation
 * - Invoice data state management and updates
 * - PDF generation and download functionality
 * - Share invoice functionality with URL generation
 * - Error handling and user feedback
 *
 * @returns The rendered invoice application page with form, preview, and controls
 */
export function AppPageClient({
  githubStarsCount,
  latestChangelog,
}: {
  githubStarsCount: number;
  latestChangelog: ChangelogSummary | null;
}) {
  const searchParams = useSearchParams();
  const pathname = usePathname();

  /**
   * The template the URL asks for: `/stripe-template`, or a legacy `?template=` on `/`.
   * `null` on a bare `/`, which has no preference: the saved invoice's template is used.
   */
  const urlTemplate = getTemplateFromUrl({ pathname, searchParams });

  const { isDesktop, isUADesktop } = useDeviceContext();
  const isMobile = !isDesktop;

  // Warns the user when they are inside an in-app browser, where downloads are blocked
  useInAppBrowserNotice();

  /**
   * State for storing the current invoice data.
   *
   * Initialized as null and populated from:
   * - localStorage on component mount
   * - URL query parameters when sharing invoice
   * - User input through the invoice form
   *
   * This state is persisted to localStorage on updates and used to generate the PDF preview.
   */
  const [invoiceDataState, setInvoiceDataState] = useState<InvoiceData | null>(
    null,
  );

  const canShareInvoice = !invoiceDataState?.logo;

  const [qrCodeDataUrl, setQrCodeDataUrl] = useState("");

  const [isInvoiceUrlCorrupted, setIsInvoiceUrlCorrupted] = useState(false);

  const isViewingSharedInvoice =
    searchParams.get("data") !== null && !isInvoiceUrlCorrupted;

  /**
   * Whether the invoice on screen is still exactly the one opened from a shared link.
   *
   * Not the same as {@link isViewingSharedInvoice}: "Get link" puts `?data=` in the address
   * bar too, but then the invoice is the user's own. Matters for "Invoice last updated",
   * which comes from this browser's metadata and the link does not carry a timestamp: for
   * an invoice opened from someone else's link it would show the viewer's own last edit.
   */
  const [isUnmodifiedInvoiceFromLink, setIsUnmodifiedInvoiceFromLink] =
    useState(false);

  const {
    isOpen: isChangelogPopupOpen,
    dismiss: dismissChangelogPopup,
    variant: changelogPopupVariant,
  } = useChangelogUpdatePopup({
    latestChangelog,
    isViewingSharedInvoice,
    canShowChangelog: !isMobile,
  });

  const [isHowItWorksDialogOpen, setIsHowItWorksDialogOpen] = useState(false);

  // One popup, placed by viewport: a floating card on desktop, a notice inside the bottom
  // dock on mobile, where a floating card would cover the dock's buttons
  const changelogPopup = changelogPopupVariant ? (
    <ChangelogUpdatePopup
      variant={changelogPopupVariant}
      isOpen={isChangelogPopupOpen}
      onDismiss={dismissChangelogPopup}
      releaseSummary={latestChangelog?.popupSummary}
      releaseSlug={latestChangelog?.slug}
      releaseVideoId={latestChangelog?.youtubeVideoId}
      layout={isMobile ? "dock" : "floating"}
      onHowItWorksClick={() => {
        return setIsHowItWorksDialogOpen(true);
      }}
    />
  ) : null;

  /**
   * Reads the invoice form at click time: its current values, or `null` when it has
   * validation errors. A ref rather than state, because the answer is only needed inside
   * handleShareInvoice — mirroring it into render would re-render the page (and the PDF)
   * on every keystroke that flips validity, and could answer with a stale value.
   */
  const currentInvoiceFormDataRef = useRef<(() => InvoiceData | null) | null>(
    null,
  );

  // Refs to track original URL invoice data
  const originalUrlInvoiceDataRef = useRef<InvoiceData | null>(null);

  // Tracks whether the invoice data has already been initialized (from URL or localStorage).
  // Initialization must happen exactly once per page load, see the effect below for details.
  const hasInitializedInvoiceDataRef = useRef(false);

  // Generate QR code data URL when qrCodeData changes
  useEffect(() => {
    // Flag to detect if the component is still mounted and effect is active
    let active = true;

    /**
     * Generates a QR code image as a data URL when QR code data is available and visible.
     * If qrCodeData or its visibility flag is missing, resets the QR code image state.
     * Handles component unmount by checking `active`.
     */
    const generateQrCode = async () => {
      // If no QR code data or QR code display is not enabled, clear the QR code image
      if (!invoiceDataState?.qrCodeData || !invoiceDataState?.qrCodeIsVisible) {
        if (active) {
          setQrCodeDataUrl("");
        }
        return;
      }

      // Generate the QR code image as a data URL for the provided data string
      const dataUrl = await generateQrCodeDataUrl(invoiceDataState.qrCodeData);

      // Set the generated QR code image if the component is still mounted
      if (active) {
        setQrCodeDataUrl(dataUrl);
      }
    };

    // Call generateQrCode when invoiceDataState.qrCodeData or invoiceDataState.qrCodeIsVisible changes
    void generateQrCode();

    // Cleanup function to set active as false on component unmount,
    // preventing state updates on an unmounted component
    return () => {
      active = false;
    };
  }, [invoiceDataState?.qrCodeData, invoiceDataState?.qrCodeIsVisible]);

  // Helper function to load from localStorage
  const loadFromLocalStorage = useCallback(() => {
    try {
      // add metadata with default values if missing for all users
      ensureAppMetadata();

      const savedData = getAppStorageItem(PDF_DATA_LOCAL_STORAGE_KEY);

      if (savedData) {
        const json: unknown = JSON.parse(savedData);

        // we patch the invoice number breaking change here
        // this should happen before parsing the data with zod
        const updatedJson = handleInvoiceNumberBreakingChange(json);

        const parsedData = invoiceSchema.parse(updatedJson);

        const selectedInvoiceData = urlTemplate
          ? selectInvoiceTemplate(parsedData, urlTemplate)
          : parsedData;

        setInvoiceDataState(selectedInvoiceData);
      } else if (urlTemplate) {
        // if no data in local storage and template is in url, set initial data with template from url
        setInvoiceDataState(getInitialInvoiceData(urlTemplate));
      } else {
        // if no data in local storage, set initial data
        setInvoiceDataState(getInitialInvoiceData());
      }
    } catch (error) {
      console.error("Failed to load saved invoice data:", error);

      // fallback to initial data on error
      setInvoiceDataState(getInitialInvoiceData(urlTemplate ?? undefined));

      toast.error(
        "Your saved invoice couldn't be loaded, so you're starting with a new one.",
        {
          id: "unable-to-load-saved-invoice-data-error-toast",
          duration: Infinity,
          closeButton: true,
          richColors: true,
        },
      );

      Sentry.captureException(error);
    }
  }, [urlTemplate]);

  useEffect(() => {
    // Scroll to top of the page on first render for better UX
    window.scrollTo({ top: 0, behavior: "smooth" });
  }, []);

  // Initialize data from URL (via shared invoice link) or localStorage on page load
  useEffect(() => {
    // Run only once per page load.
    //
    // This effect depends on `searchParams`, and the app rewrites the URL on its own
    // (e.g. to keep the template's route in sync, or to add ?data=
    // when a share link is generated). Without this guard, every one of those rewrites
    // re-ran the initialization, re-read localStorage and called `setInvoiceDataState`
    // with a brand new (but identical) object. That extra state update makes react-pdf
    // regenerate the very same PDF a second time, which shows up as a visible flicker /
    // double render in the preview when the user switches the invoice template.
    if (hasInitializedInvoiceDataRef.current) {
      return;
    }

    hasInitializedInvoiceDataRef.current = true;

    const compressedInvoiceDataInUrl = searchParams.get("data");

    // first try to load from url i.e. if user has shared invoice link
    if (compressedInvoiceDataInUrl) {
      debugLog("[useEffect] [initialize invoice data from ** URL **]");

      try {
        const decompressedData = decompressFromEncodedURIComponent(
          compressedInvoiceDataInUrl,
        );

        const parsedJSON: unknown = JSON.parse(decompressedData);

        // Restore original keys from compressed format, we store keys in compressed format to reduce URL size i.e. {name: "John Doe"} -> {n: "John Doe"}
        const decompressedKeys = decompressInvoiceData(
          parsedJSON as Record<string, unknown>,
        );

        // we patch the invoice number breaking change here (this should happen before parsing the data with zod)
        const updatedJson = handleInvoiceNumberBreakingChange(decompressedKeys);

        const validatedDataFromURL = invoiceSchema.parse(updatedJson);

        debugLog(
          "[useEffect] [initialize invoice data from ** URL **] validatedDataFromURL",
          validatedDataFromURL,
        );

        // Override template from the URL (`/stripe-template` or ?template=) if present for
        // better UX, while ?data contains the actual invoice data including the template.
        // The URL template has higher priority than ?data=" " =)
        const selectedInvoiceData = urlTemplate
          ? selectInvoiceTemplate(validatedDataFromURL, urlTemplate)
          : validatedDataFromURL;

        setInvoiceDataState(selectedInvoiceData);

        // Store the original URL invoice data for change detection
        originalUrlInvoiceDataRef.current = selectedInvoiceData;
        setIsUnmodifiedInvoiceFromLink(true);

        // add metadata with default values if missing for all users
        ensureAppMetadata();
      } catch (error) {
        console.error(
          "[useEffect] [initialize invoice data from ** URL **] Failed to parse URL data:",
          error,
        );
        // fallback to local storage in case of error
        loadFromLocalStorage();

        setIsInvoiceUrlCorrupted(true);

        toast.error("The shared invoice URL appears to be incorrect", {
          id: "invalid-invoice-url-error-toast", // prevent duplicate toasts
          description: (
            <div className="flex flex-col gap-2">
              <p className="">
                Please verify that you have copied the complete invoice URL. The
                link may be truncated or corrupted.
              </p>
              <p className="">Try generating a new link.</p>
              <Button
                variant="outline"
                size="sm"
                onClick={() => {
                  // drop the corrupted `?data=`, keep everything else the visitor arrived with
                  const clearedParams = new URLSearchParams(
                    window.location.search,
                  );
                  clearedParams.delete("data");

                  replaceUrl(
                    buildInvoiceAppUrl({
                      template:
                        getTemplateFromUrl({
                          pathname: window.location.pathname,
                          searchParams: clearedParams,
                        }) ?? "default",
                      searchParams: clearedParams,
                    }),
                  );

                  toast.dismiss();
                }}
              >
                Clear URL
              </Button>
            </div>
          ),
          duration: 20_000,
          closeButton: true,
        });

        Sentry.captureException(error);
      }
    } else {
      debugLog(
        "[useEffect] [initialize invoice data from ** LOCAL STORAGE **]",
      );

      // if no data in url, load from local storage
      loadFromLocalStorage();
    }
  }, [loadFromLocalStorage, searchParams, urlTemplate]);

  /**
   * Ensures the URL is the route of the loaded invoice's template (for better user
   * experience): `/` or `/stripe-template`. A visitor landing on a bare `/` with a saved
   * Stripe invoice is moved to `/stripe-template`, and legacy links drop their now
   * redundant `?template=` (`/?template=default`, or `/?template=stripe` after its
   * redirect to `/stripe-template?template=stripe`).
   */
  useEffect(() => {
    // `no-event-handler` wants this written where the invoice data is set, but the template
    // being written *is* `invoiceDataState.template`, which the initialization effect has not
    // resolved yet at that point. (It was also load-bearing back when this used
    // `router.replace`, which the App Router dropped when called mid-mount -- under load the
    // shared-link e2e tests then sat on a URL that never grew its `?template=`.)
    // oxlint-disable-next-line react-you-might-not-need-an-effect/no-event-handler
    if (!invoiceDataState) {
      return;
    }

    // Read the address bar itself, not `pathname`/`searchParams`: Next syncs those with
    // `history.replaceState` a render later, so right after a template switch this effect
    // sees the new invoice template next to the *previous* URL. Rebuilding from that stale
    // URL put back the `?data=` that `handleInvoiceDataChange` had just dropped, leaving an
    // edited invoice on its old share link.
    const currentParams = new URLSearchParams(window.location.search);

    if (
      isUrlForTemplate({
        template: invoiceDataState.template,
        pathname: window.location.pathname,
        searchParams: currentParams,
      })
    ) {
      return;
    }

    const expectedUrl = buildInvoiceAppUrl({
      template: invoiceDataState.template,
      searchParams: currentParams,
    });

    debugLog("[useEffect] [sync template to URL]", {
      template: invoiceDataState.template,
      expectedUrl,
    });

    // Update the browser URL without triggering a page reload or scroll
    replaceUrl(expectedUrl);
  }, [invoiceDataState]);

  /**
   * Keeps the tab title and the canonical URL on the route in the address bar. Both come
   * from the metadata of the route the page was *loaded* on, and a template switch only
   * rewrites the URL, so a bare `/` that moved on to `/stripe-template` (a saved Stripe
   * invoice), or a switch in the template picker, would keep the other route's -- the
   * title is what a bookmark or a history entry gets, and the canonical is what Safari's
   * own Share (in its menu, not "Get link") copies instead of the address bar.
   *
   * Crawlers never see the rewrite: they have no saved invoice and don't switch templates.
   *
   * An effect on `pathname` rather than a write in `replaceUrl`: Next re-renders the tree
   * to sync `usePathname()` with `history.replaceState`, and React puts the metadata's
   * `<title>` back in that commit. This runs after it.
   *
   * Known gap: on a client-side navigation into the app (e.g. "Open app" from another
   * page), Next can commit the route's metadata later still, putting the loaded route's
   * title and canonical back.
   */
  useEffect(() => {
    const routeTemplate = getRouteTemplate(pathname);

    document.title = APP_PAGE_TITLE[routeTemplate];

    const canonicalLink = document.querySelector<HTMLLinkElement>(
      'link[rel="canonical"]',
    );

    if (canonicalLink) {
      // resolved against the current canonical to keep its origin: `APP_URL` comes from a
      // server-only env var, so the client bundle cannot build it
      canonicalLink.href = new URL(
        buildInvoiceAppUrl({ template: routeTemplate }),
        canonicalLink.href,
      ).href;
    }
  }, [pathname]);

  /**
   * Checks if the invoice has changed from the original shared URL version.
   * Shows a toast notification once and cleans the URL when changes are detected.
   */
  const checkForInvoiceChanges = useCallback(
    (currentData: InvoiceData) => {
      debugLog("[checkForInvoiceChanges]", currentData.template, {
        originalUrlInvoiceDataRef: originalUrlInvoiceDataRef.current,
      });

      // Check if URL has data i.e. if user has shared invoice link
      const urlData = searchParams.get("data");

      // Skip if no original URL data or no data in url
      if (!originalUrlInvoiceDataRef.current || !urlData) {
        debugLog("[checkForInvoiceChanges] skipping");

        return;
      }

      // TODO: Improve this check, by using more reliable way to compare the invoice data (i.e. using npm lib)
      const invoiceHasChanged =
        JSON.stringify(originalUrlInvoiceDataRef.current) !==
        JSON.stringify(currentData);

      if (invoiceHasChanged) {
        debugLog("[checkForInvoiceChanges] invoice has changed");

        // the edit that got us here also stamped a fresh "Invoice last updated"
        setIsUnmodifiedInvoiceFromLink(false);

        // the link they confirm no longer matches the invoice
        for (const toastId of Object.values(SHARE_LINK_SUCCESS_TOAST_IDS)) {
          toast.dismiss(toastId);
        }

        toast.info(
          <div className="space-y-2">
            <p className="text-sm font-semibold">Invoice Updated</p>
            <p className="text-muted-foreground text-pretty leading-relaxed">
              Your changes have modified this invoice from its shared version.
            </p>

            <p className="text-muted-foreground text-pretty leading-relaxed">
              Click{" "}
              <span className="font-semibold underline underline-offset-2">
                Get link
              </span>{" "}
              to create an updated shareable link.
            </p>
          </div>,
          {
            id: INVOICE_UPDATED_TOAST_ID,
            duration: 20_000,
            closeButton: true,
            position: isMobile ? "top-center" : "bottom-right",
          },
        );

        // Remove the ?data parameter from URL since the invoice has been modified (clean url, because it's no longer valid)
        const currentParams = new URLSearchParams(searchParams.toString());
        currentParams.delete("data");

        // Update the browser URL without triggering a page reload or scroll
        // This keeps the URL in sync with the invoice state while maintaining user position
        replaceUrlQuery(currentParams);
      }
    },
    [isMobile, searchParams],
  );

  /**
   * Handles changes to the invoice data.
   *
   * This function:
   * - Updates the invoice state (useState hook) with the new data
   * - Handles invoice URL corruption by clearing invalid URL parameters and notifying the user
   * - Triggers change detection to show toast if invoice is modified from the URL-loaded version
   *
   * Stable across renders on purpose: `InvoiceForm` is wrapped in `memo`, and this function
   * is one of its props. As a fresh closure on every render it made that `memo` unable to
   * ever hold, so re-renders that have nothing to do with the invoice -- opening the "How it
   * works" dialog, the changelog popup, a regenerated QR code -- re-rendered the whole form.
   * The form still re-renders when its own edit comes back through `invoiceDataState`, which
   * is inherent to that round trip.
   */
  const handleInvoiceDataChange = useCallback(
    (updatedData: InvoiceData) => {
      debugLog("[handleInvoiceDataChange]");

      if (isInvoiceUrlCorrupted) {
        debugLog("[handleInvoiceDataChange] clearing url due to corruption");

        /** CLEAR URL IN CASE OF CORRUPTED INVOICE URL (i.e. "/?data=") for better UX and consistency */

        // Remove the ?data parameter from URL since the invoice has been modified (clean url, because it's no longer valid)
        const currentParams = new URLSearchParams(searchParams.toString());
        currentParams.delete("data");

        // update the url
        replaceUrlQuery(currentParams);

        // Show notification that URL was cleared due to corruption
        toast.info(
          <div className="space-y-2">
            <p className="text-sm font-semibold">Corrupted URL Cleared</p>
            <p className="text-muted-foreground text-pretty leading-relaxed">
              The invalid invoice URL has been removed from the address bar.
            </p>
            <p className="text-muted-foreground text-pretty leading-relaxed">
              Click{" "}
              <span className="font-semibold text-foreground">
                &apos;Get link&apos;
              </span>{" "}
              to create a new shareable link.
            </p>
          </div>,
          {
            id: "corrupted-url-cleared-toast",
            duration: 15_000,
            closeButton: true,
            position: isMobile ? "top-center" : "bottom-right",
          },
        );

        // Reset the invoice url corruption state
        setIsInvoiceUrlCorrupted(false);
      }

      setInvoiceDataState(updatedData);
      checkForInvoiceChanges(updatedData);

      // The template of the route in the address bar: read from `window.location`, which
      // is never stale (unlike `pathname`, see the URL sync effect), and from the route
      // alone -- a legacy `?template=` the sync effect has not dropped yet is not a switch.
      const currentTemplate = getRouteTemplate(window.location.pathname);

      // update the url with the new template
      if (currentTemplate !== updatedData.template) {
        debugLog("[handleInvoiceDataChange] update url with new template", {
          currentTemplate,
          updatedDataTemplate: updatedData.template,
        });

        // Rebuilt from the current params rather than replacing the whole query string:
        // this used to be a bare `/?template=...`, which also threw away anything else the
        // visitor arrived with (utm tags and the like). `data` is still dropped on purpose --
        // a template switch is a change from the shared version, which is exactly what
        // `checkForInvoiceChanges` above has just told the user about.
        const templateParams = new URLSearchParams(window.location.search);
        templateParams.delete("data");

        // moves between `/` and `/stripe-template`
        replaceUrl(
          buildInvoiceAppUrl({
            template: updatedData.template,
            searchParams: templateParams,
          }),
        );
      } else {
        debugLog("[handleInvoiceDataChange] invoice template did not change");
      }
    },
    [checkForInvoiceChanges, isInvoiceUrlCorrupted, isMobile, searchParams],
  );

  /** Generate a shareable invoice link */
  const handleShareInvoice = useCallback(async () => {
    if (!canShareInvoice) {
      toast.error("Unable to Share Invoice", {
        id: "unable-to-share-invoice-error-toast",
        duration: 10_000,
        description: (
          <p className="text-pretty text-xs leading-relaxed text-red-700">
            {CANNOT_SHARE_INVOICE_DESCRIPTION}
          </p>
        ),
      });

      return;
    }

    // Read the form directly rather than trusting `invoiceDataState`, which only catches
    // up on the DEBOUNCE_TIMEOUT commit: a click inside that window would otherwise share
    // the pre-edit snapshot, and the edit landing a moment later would strip ?data= again
    // via checkForInvoiceChanges. Falls back to `invoiceDataState` when the form is not
    // mounted (mobile opens on the preview tab), where the tab switch has already flushed.
    const currentInvoiceData = currentInvoiceFormDataRef.current
      ? currentInvoiceFormDataRef.current()
      : invoiceDataState;

    // prevent sharing invoice if there are form errors
    if (!currentInvoiceData) {
      toast.error("Unable to Share Invoice", {
        id: "unable-to-share-invoice-form-errors-toast",
        duration: 6000,
        position: isMobile ? "top-center" : "bottom-right",
        description: (
          <p className="text-pretty text-xs leading-relaxed text-red-700">
            Please fix the errors in the invoice form to generate a shareable
            link.
          </p>
        ),
      });

      return;
    }

    // if invoice data state is valid, generate the shareable link and update the url
    if (currentInvoiceData) {
      try {
        const newInvoiceDataValidated = invoiceSchema.parse(currentInvoiceData);

        // trigger haptic feedback on mobile devices
        haptic();

        // Compress JSON keys before stringifying to reduce URL size
        const compressedKeys = compressInvoiceData(newInvoiceDataValidated);
        const compressedJson = JSON.stringify(compressedKeys);

        const compressedData = compressToEncodedURIComponent(compressedJson);

        /**
         * Check if the compressed data length exceeds browser URL limits.
         * With key compression, we can fit much larger invoices within this limit.
         */
        const URL_LENGTH_LIMIT = 4096;

        const estimatedUrlLength =
          window.location.origin.length + 7 + compressedData.length; // 7 for "/?data="

        if (estimatedUrlLength > URL_LENGTH_LIMIT) {
          toast.error("Invoice data is too large to share via URL", {
            id: "invoice-data-too-large-to-share-via-url-error-toast",
            description:
              "Download the invoice as PDF instead or remove some invoice items and try again.",
            duration: 10_000,
            position: isMobile ? "top-center" : "bottom-right",
          });

          return;
        }

        const currentParams = new URLSearchParams(searchParams.toString());
        currentParams.set("data", compressedData);

        const sharedInvoiceUrl = buildInvoiceAppUrl({
          template: newInvoiceDataValidated.template,
          searchParams: currentParams,
        });

        replaceUrl(sharedInvoiceUrl);

        // Remember the invoice that was just shared, so later edits are detected and the
        // "Invoice Updated" toast is shown. Previously this ref was (re)populated as a
        // side effect of the initialization effect re-running on the ?data= URL change,
        // which no longer happens now that initialization runs once per page load.
        originalUrlInvoiceDataRef.current = newInvoiceDataValidated;

        // A new link makes "Invoice Updated" stale. It has to go before the next edit, too:
        // the form dismisses that toast on every change, right before this page shows it again
        // under the same id, and sonner treats that as an update to the toast on its way out --
        // so a second share-then-edit in one session used to end with no toast at all. It also
        // lets the success toast below come to the front: with `visibleToasts={1}` a toast
        // updated in place under an existing id stays wherever it was in the stack.
        toast.dismiss(INVOICE_UPDATED_TOAST_ID);

        // Construct full URL with locale and compressed data
        const newGeneratedLinkFullUrl = `${window.location.origin}${sharedInvoiceUrl}`;

        // allow sharing invoice via navigator.share (on mobile and tablet) or copy to clipboard (on desktop)
        if (!isUADesktop && navigator?.share) {
          // MOBILE + TABLET
          try {
            toast.success("Your invoice link is ready. Share it now.", {
              id: SHARE_LINK_SUCCESS_TOAST_IDS.shareSheet,
              description: (
                <p data-testid="share-invoice-link-description-toast">
                  Share this link to let others view and edit this invoice
                </p>
              ),
              position: isMobile ? "top-center" : "bottom-right",
              duration: 10_000,
            });

            await navigator
              ?.share({
                title: "Your invoice link is ready. Share it now.",
                url: newGeneratedLinkFullUrl,
              })
              .then(() => {
                umamiTrackEvent("share_invoice_link_mobile");

                updateAppMetadata((current) => {
                  return {
                    ...current,
                    invoiceSharedCount: (current?.invoiceSharedCount ?? 0) + 1,
                  };
                });

                // dismiss other toasts when navigator.share is successful (for better UX)
                setTimeout(() => {
                  toast.dismiss();
                }, 1500);
              })
              .catch((error) => {
                console.error(
                  "[handleShareInvoice] failed to share invoice:",
                  error,
                );

                // dismiss all other toasts for better UX
                toast.dismiss();

                // Only show error if it's not an abort error (user cancelled the share)
                if (error instanceof Error && error?.name !== "AbortError") {
                  toast.error("Failed to share invoice", {
                    id: "failed-to-share-invoice-error-toast",
                    description: `Please try again or copy the link manually from the address bar`,
                    position: isMobile ? "top-center" : "bottom-right",
                    duration: 5000,
                  });

                  Sentry.captureException(error);
                }
              });
          } catch (shareError) {
            console.error(
              "[handleShareInvoice] failed to share invoice:",
              shareError,
            );
            // Optionally fall back to clipboard on share cancel/error
            await navigator?.clipboard?.writeText(newGeneratedLinkFullUrl);
          }
        } else {
          // DESKTOP

          // on desktop, copy to clipboard
          await navigator?.clipboard
            ?.writeText(newGeneratedLinkFullUrl)
            .then(() => {
              toast.success("Invoice link generated and copied to clipboard!", {
                id: SHARE_LINK_SUCCESS_TOAST_IDS.clipboard,
                description: (
                  <p data-testid="share-invoice-link-description-toast">
                    Share this link to let others view and edit this invoice
                  </p>
                ),
                position: isMobile ? "top-center" : "bottom-right",
                duration: 5000,
              });

              umamiTrackEvent("share_invoice_link");

              updateAppMetadata((current) => {
                return {
                  ...current,
                  invoiceSharedCount: (current?.invoiceSharedCount ?? 0) + 1,
                };
              });
            })
            .catch((error) => {
              Sentry.captureException(error);
            });
        }
      } catch (error) {
        console.error("Failed to share invoice:", error);
        toast.error("Failed to generate shareable link", {
          id: "failed-to-generate-shareable-link-error-toast",
        });

        Sentry.captureException(error);
      }
    }
  }, [canShareInvoice, invoiceDataState, isMobile, isUADesktop, searchParams]);

  // we only want to render the page on client side
  if (!invoiceDataState) {
    return <InvoicePageLoadingSkeleton />;
  }

  return (
    <TooltipProvider delayDuration={0}>
      {/* Generates the invoice PDF once and shares it with the preview and the download button */}
      <InvoicePdfInstanceProvider
        invoiceData={invoiceDataState}
        qrCodeDataUrl={qrCodeDataUrl}
      >
        <main className="flex flex-col items-center justify-start bg-gray-100 pb-4 sm:p-4 md:justify-center lg:min-h-screen">
          <div className="w-full max-w-[62rem] bg-white p-3 shadow-lg sm:mb-0 sm:rounded-lg sm:p-6 sm:pb-1 min-[1400px]:max-w-7xl 2xl:max-w-[1480px]">
            <InvoicePageHeader
              canShareInvoice={canShareInvoice}
              handleShareInvoice={handleShareInvoice}
              isDesktop={isDesktop}
              invoiceDataState={invoiceDataState}
              isMobile={isMobile}
              isSharedInvoice={isViewingSharedInvoice}
            />
            <div className="grid grid-cols-1 gap-4 lg:grid-cols-12">
              <InvoiceClientPage
                invoiceDataState={invoiceDataState}
                handleInvoiceDataChange={handleInvoiceDataChange}
                handleShareInvoice={handleShareInvoice}
                isMobile={isMobile}
                canShareInvoice={canShareInvoice}
                currentInvoiceFormDataRef={currentInvoiceFormDataRef}
                isUnmodifiedInvoiceFromLink={isUnmodifiedInvoiceFromLink}
                mobileDockNotice={isMobile ? changelogPopup : null}
                // switching tabs means the user found their way around, so the welcome
                // notice has done its job
                onMobileTabChange={dismissChangelogPopup}
              />
            </div>
          </div>
        </main>
      </InvoicePdfInstanceProvider>
      {isMobile ? null : changelogPopup}
      <HowItWorksVideoDialog
        open={isHowItWorksDialogOpen}
        onOpenChange={setIsHowItWorksDialogOpen}
      />
      <div className="fixed right-1.5 top-1.5 z-50 duration-500 animate-in fade-in slide-in-from-top-4">
        <GitHubStarCTA githubStarsCount={githubStarsCount} />
      </div>
    </TooltipProvider>
  );
}

/**
 * The "Invoice Updated" toast: the invoice no longer matches the shared link it was opened
 * from (or that was just generated). `invoice-form/index.tsx` dismisses it by this id on
 * every change.
 */
const INVOICE_UPDATED_TOAST_ID = "invoice-has-changed-toast";

/** The toasts confirming a share link: the share sheet (mobile) and the clipboard (desktop). */
const SHARE_LINK_SUCCESS_TOAST_IDS = {
  shareSheet: "invoice-link-generated-share-invoice-success-toast",
  clipboard: "invoice-link-copied-to-clipboard-success-toast",
} as const;