<script lang="ts">
  import { afterNavigate, beforeNavigate } from '$app/navigation';
  import { page } from '$app/stores';
  import { resizeObserver, type OnResizeCallback } from '$lib/actions/resize-observer';
  import Hmr from '$lib/components/timeline/base-components/hmr.svelte';
  import Skeleton from '$lib/components/timeline/base-components/skeleton.svelte';
  import SelectableTimelineMonth from '$lib/components/timeline/internal-components/selectable-timeline-month.svelte';
  import type { DayGroup } from '$lib/managers/timeline-manager/day-group.svelte';
  import type { MonthGroup } from '$lib/managers/timeline-manager/month-group.svelte';
  import { TimelineManager } from '$lib/managers/timeline-manager/timeline-manager.svelte';
  import type { TimelineAsset } from '$lib/managers/timeline-manager/types';
  import type { AssetInteraction } from '$lib/stores/asset-interaction.svelte';
  import { assetViewingStore } from '$lib/stores/asset-viewing.store';
  import { mobileDevice } from '$lib/stores/mobile-device.svelte';
  import { onMount, type Snippet } from 'svelte';
  import type { UpdatePayload } from 'vite';

  interface Props {
    customThumbnailLayout?: Snippet<[TimelineAsset]>;

    isSelectionMode?: boolean;
    singleSelect?: boolean;
    /** `true` if this asset grid responds to navigation events; if `true`, then look at the
     `AssetViewingStore.gridScrollTarget` and load and scroll to the asset specified, and
     additionally, update the page location/url with the asset as the asset-grid is scrolled */
    enableRouting: boolean;
    timelineManager: TimelineManager;
    assetInteraction: AssetInteraction;
    withStacked?: boolean;
    showArchiveIcon?: boolean;
    showSkeleton?: boolean;
    isShowDeleteConfirmation?: boolean;
    styleMarginRightOverride?: string;
    onAssetOpen?: (dayGroup: DayGroup, asset: TimelineAsset, defaultAssetOpen: () => void) => void;
    onSelect?: (asset: TimelineAsset) => void;
    header?: Snippet<[scrollToFunction: (top: number) => void]>;
    children?: Snippet;
    empty?: Snippet;
    handleTimelineScroll?: () => void;
  }

  let {
    customThumbnailLayout,

    isSelectionMode = false,
    singleSelect = false,
    enableRouting,
    timelineManager = $bindable(),
    assetInteraction,
    withStacked = false,
    showSkeleton = $bindable(true),
    showArchiveIcon = false,
    styleMarginRightOverride,
    isShowDeleteConfirmation = $bindable(false),

    onAssetOpen,
    onSelect,
    children,
    empty,
    header,
    handleTimelineScroll = () => {},
  }: Props = $props();

  let { gridScrollTarget } = assetViewingStore;

  let element: HTMLElement | undefined = $state();
  let timelineElement: HTMLElement | undefined = $state();

  const maxMd = $derived(mobileDevice.maxMd);
  const isEmpty = $derived(timelineManager.isInitialized && timelineManager.months.length === 0);

  $effect(() => {
    const layoutOptions = maxMd
      ? {
          rowHeight: 100,
          headerHeight: 32,
        }
      : {
          rowHeight: 235,
          headerHeight: 48,
        };
    timelineManager.setLayoutOptions(layoutOptions);
  });

  const scrollTo = (top: number) => {
    if (element) {
      element.scrollTo({ top });
    }
    updateSlidingWindow();
  };

  const scrollBy = (y: number) => {
    if (element) {
      element.scrollBy(0, y);
    }
    updateSlidingWindow();
  };

  const scrollCompensation = (compensation: { heightDelta?: number; scrollTop?: number }) => {
    const { heightDelta, scrollTop } = compensation;
    if (heightDelta !== undefined) {
      scrollBy(heightDelta);
    } else if (scrollTop !== undefined) {
      scrollTo(scrollTop);
    }
    timelineManager.clearScrollCompensation();
  };

  const getAssetHeight = (assetId: string, monthGroup: MonthGroup) => {
    // the following method may trigger any layouts, so need to
    // handle any scroll compensation that may have been set
    const height = monthGroup!.findAssetAbsolutePosition(assetId);

    // this is in a while loop, since scrollCompensations invoke scrolls
    // which may load months, triggering more scrollCompensations. Call
    // this in a loop, until no more layouts occur.
    while (timelineManager.scrollCompensation.monthGroup) {
      scrollCompensation(timelineManager.scrollCompensation);
    }
    return height;
  };

  const assetIsVisible = (assetTop: number): boolean => {
    if (!element) {
      return false;
    }

    const { clientHeight, scrollTop } = element;
    return assetTop >= scrollTop && assetTop < scrollTop + clientHeight;
  };

  const scrollToAssetId = async (assetId: string) => {
    const monthGroup = await timelineManager.findMonthGroupForAsset(assetId);
    if (!monthGroup) {
      return false;
    }
    const height = getAssetHeight(assetId, monthGroup);

    // If the asset is already visible, then don't scroll.
    if (assetIsVisible(height)) {
      return true;
    }

    scrollTo(height);
    return true;
  };

  export const scrollToAsset = (asset: TimelineAsset) => {
    const monthGroup = timelineManager.getMonthGroupByAssetId(asset.id);
    if (!monthGroup) {
      return false;
    }
    const height = getAssetHeight(asset.id, monthGroup);
    scrollTo(height);
    return true;
  };

  const completeNav = async () => {
    const scrollTarget = $gridScrollTarget?.at;
    let scrolled = false;
    if (scrollTarget) {
      scrolled = await scrollToAssetId(scrollTarget);
    }
    if (!scrolled) {
      // if the asset is not found, scroll to the top
      scrollTo(0);
    }
    showSkeleton = false;
  };

  beforeNavigate(() => (timelineManager.suspendTransitions = true));

  afterNavigate((nav) => {
    const { complete } = nav;
    complete.then(completeNav, completeNav);
  });

  const updateIsScrolling = () => (timelineManager.scrolling = true);
  // Yes, updateSlideWindow() is called by the onScroll event. However, if you also just scrolled
  // by explicitly invoking element.scrollX functions, there may be a delay with enough time to
  // set the intersecting property of the monthGroup to false, then true, which causes the DOM
  // nodes to be recreated, causing bad perf, and also, disrupting focus of those elements.
  // Also note: don't throttle, debounce, or otherwise do this function async - it causes flicker
  const updateSlidingWindow = () => timelineManager.updateSlidingWindow(element?.scrollTop || 0);

  const topSectionResizeObserver: OnResizeCallback = ({ height }) => (timelineManager.topSectionHeight = height);

  onMount(() => {
    if (!enableRouting) {
      showSkeleton = false;
    }
  });
</script>

<Hmr
  onAfterUpdate={(payload: UpdatePayload) => {
    // when hmr happens, skeleton is initialized to true by default
    // normally, loading asset-grid is part of a navigation event, and the completion of
    // that event triggers a scroll-to-asset, if necessary, when then clears the skeleton.
    // this handler will run the navigation/scroll-to-asset handler when hmr is performed,
    // preventing skeleton from showing after hmr
    const finishHmr = () => {
      const asset = $page.url.searchParams.get('at');
      if (asset) {
        $gridScrollTarget = { at: asset };
      }
      void completeNav();
    };
    const assetGridUpdate = payload.updates.some((update) => update.path.endsWith('base-timeline-viewer.svelte'));
    if (assetGridUpdate) {
      // wait 500ms for the update to be fully swapped in
      setTimeout(finishHmr, 500);
    }
  }}
/>

{@render header?.(scrollTo)}

<!-- Right margin MUST be equal to the width of scrubber -->
<section
  id="asset-grid"
  class={['scrollbar-hidden h-full overflow-y-auto outline-none', { 'm-0': isEmpty }, { 'ms-0': !isEmpty }]}
  style:margin-right={styleMarginRightOverride}
  tabindex="-1"
  bind:clientHeight={timelineManager.viewportHeight}
  bind:clientWidth={null, (v: number) => ((timelineManager.viewportWidth = v), updateSlidingWindow())}
  bind:this={element}
  onscroll={() => (handleTimelineScroll(), updateSlidingWindow(), updateIsScrolling())}
>
  <section
    bind:this={timelineElement}
    id="virtual-timeline"
    class:invisible={showSkeleton}
    style:height={timelineManager.timelineHeight + 'px'}
  >
    <section
      use:resizeObserver={topSectionResizeObserver}
      class:invisible={showSkeleton}
      style:position="absolute"
      style:left="0"
      style:right="0"
    >
      {@render children?.()}
      {#if isEmpty}
        <!-- (optional) empty placeholder -->
        {@render empty?.()}
      {/if}
    </section>

    {#each timelineManager.months as monthGroup (monthGroup.viewId)}
      {@const display = monthGroup.intersecting}
      {@const absoluteHeight = monthGroup.top}

      {#if !monthGroup.isLoaded}
        <div
          style:height={monthGroup.height + 'px'}
          style:position="absolute"
          style:transform={`translate3d(0,${absoluteHeight}px,0)`}
          style:width="100%"
        >
          <Skeleton
            height={monthGroup.height - monthGroup.timelineManager.headerHeight}
            title={monthGroup.monthGroupTitle}
          />
        </div>
      {:else if display}
        <div
          class="month-group"
          style:height={monthGroup.height + 'px'}
          style:position="absolute"
          style:transform={`translate3d(0,${absoluteHeight}px,0)`}
          style:width="100%"
        >
          <SelectableTimelineMonth
            {customThumbnailLayout}
            {withStacked}
            {showArchiveIcon}
            {assetInteraction}
            {timelineManager}
            {isSelectionMode}
            {singleSelect}
            {monthGroup}
            {onAssetOpen}
            onSelect={(isSingleSelect: boolean, asset: TimelineAsset) => {
              if (isSingleSelect) {
                scrollTo(0);
              }
              onSelect?.(asset);
            }}
            onScrollCompensationMonthInDOM={scrollCompensation}
          />
        </div>
      {/if}
    {/each}
    <!-- spacer for lead-out -->
    <div
      class="h-[60px]"
      style:position="absolute"
      style:left="0"
      style:right="0"
      style:transform={`translate3d(0,${timelineManager.timelineHeight}px,0)`}
    ></div>
  </section>
</section>

<style>
  #asset-grid {
    contain: strict;
    scrollbar-width: none;
  }

  .month-group {
    contain: layout size paint;
    transform-style: flat;
    backface-visibility: hidden;
    transform-origin: center center;
  }
</style>
