<script lang="ts">
  import Stack from "../stack/Stack.svelte";
  import { useConditionContext } from "../../stores/condition-context.svelte";
  import { setLoaderContext, type LoaderContextValue } from "../../stores/loader";
  import { getPaywallContext } from "../../stores/paywall";
  import type { LoaderProps } from "../../types/components/loader";
  import { resolveOverrideProperties } from "../../utils/style-utils";
  import { untrack } from "svelte";
  import { writable } from "svelte/store";

  import { sharedFrameNow } from "./shared-frame-ticker";

  const props: LoaderProps = $props();

  const { onButtonAction } = getPaywallContext();
  const buildConditionContext = useConditionContext({ state: true });
  const actualProps = $derived({
    ...props,
    ...resolveOverrideProperties(buildConditionContext(), props.overrides),
  });

  // Publishes progress (0–1) only; geometry belongs to the animation.
  const loaderStore = writable<LoaderContextValue>({ progress: 0 });
  setLoaderContext(loaderStore);

  const isVisible = $derived(actualProps.visible !== false);

  // Gated by visibility so a hidden loader can't dispatch in the background.
  // untrack: the store's synchronous replay would otherwise make actualProps
  // a dependency too, restarting the timer on any unrelated state change.
  $effect(() => {
    if (!isVisible) return;

    return untrack(() => {
      let fired = false;
      let unsubscribe: (() => void) | undefined;
      let dispatchFrame: number | undefined;

      // Stamp startTs at subscribe time — the shared store replays its
      // current value to new subscribers, which is not this loader's start.
      const startTs = performance.now();

      const onFrame = (now: number) => {
        const elapsed = Math.max(0, now - startTs);
        const next = Math.min(1, elapsed / Math.max(1, actualProps.loading_duration_ms));
        loaderStore.set({ progress: next });
        if (next < 1 || fired) return;

        fired = true;
        // Detach before dispatching; the action unmounts this screen.
        unsubscribe?.();
        unsubscribe = undefined;

        // Pass own id for workflow actions, matching ButtonNode's convention.
        const actionId = actualProps.action.type === "workflow" ? actualProps.id : undefined;
        // Defer past the next paint so a loader_progress_components entry at
        // appears_at: 100 gets a chance to render before navigation unmounts.
        dispatchFrame = requestAnimationFrame(() => onButtonAction(actualProps.action, actionId));
      };

      unsubscribe = sharedFrameNow.subscribe(onFrame);

      return () => {
        unsubscribe?.();
        if (dispatchFrame !== undefined) cancelAnimationFrame(dispatchFrame);
      };
    });
  });
</script>

{#if isVisible}
  <Stack {...actualProps.stack} testId="loader" />
{/if}
