import { type JSX, createSignal, splitProps } from "solid-js";
import { For } from "solid-js";
import { createVirtualizer } from "../../primitives/create-virtualizer";
import type { VirtualListRootProps } from "./virtual-list.props";

/** Root scroll container for VirtualList. Renders only visible items via createVirtualizer. */
export function VirtualListRoot(props: VirtualListRootProps): JSX.Element {
  const [local, rest] = splitProps(props, ["count", "estimateSize", "overscan", "horizontal", "children", "style"]);
  const [scrollEl, setScrollEl] = createSignal<HTMLElement | null>(null);

  const estimateFn = () => {
    const e = local.estimateSize;
    if (typeof e === "function") return e;
    const size = typeof e === "number" ? e : 40;
    return (_i: number) => size;
  };

  const virtualizer = createVirtualizer({
    count: () => local.count,
    getScrollElement: scrollEl,
    estimateSize: (i) => estimateFn()(i),
    overscan: local.overscan,
    horizontal: local.horizontal,
  });

  const axis = () => (local.horizontal ? "width" : "height");
  const posKey = () => (local.horizontal ? "left" : "top");

  return (
    <div
      data-scope="virtual-list"
      data-part="root"
      ref={setScrollEl}
      style={{ overflow: "auto", position: "relative", ...((local.style as object) ?? {}) }}
      {...rest}
    >
      <div
        data-part="inner"
        style={{ [axis()]: `${virtualizer.totalSize()}px`, position: "relative" }}
      >
        <For each={virtualizer.virtualItems()}>
          {(item) => (
            <div
              data-part="item"
              data-index={item.index}
              ref={(el) => virtualizer.measureElement(el)}
              style={{ position: "absolute", [posKey()]: `${item.start}px`, width: local.horizontal ? undefined : "100%" }}
            >
              {local.children(item)}
            </div>
          )}
        </For>
      </div>
    </div>
  );
}
