import type { JSX } from "solid-js";
import { For, splitProps } from "solid-js";
import { usePaginationContext } from "./pagination-context";

/** Represents a single item in the pagination list. */
export interface PaginationItemData {
  type: "page" | "ellipsis";
  page?: number;
  isActive: boolean;
}

/** Props for Pagination.Items. */
export interface PaginationItemsProps {
  /** Render prop called for each item in the page list. */
  children: (item: PaginationItemData) => JSX.Element;
}

/**
 * Builds the flat list of page items to render, given current page state.
 * Always-visible: first and last pages. Middle pages depend on siblingCount.
 */
function buildItems(page: number, total: number, siblings: number): PaginationItemData[] {
  if (total <= 1) return [{ type: "page", page: 1, isActive: page === 1 }];

  const pages: PaginationItemData[] = [];
  const leftSibling = Math.max(2, page - siblings);
  const rightSibling = Math.min(total - 1, page + siblings);

  pages.push({ type: "page", page: 1, isActive: page === 1 });

  if (leftSibling > 2) {
    pages.push({ type: "ellipsis", isActive: false });
  }

  for (let p = leftSibling; p <= rightSibling; p++) {
    pages.push({ type: "page", page: p, isActive: p === page });
  }

  if (rightSibling < total - 1) {
    pages.push({ type: "ellipsis", isActive: false });
  }

  pages.push({ type: "page", page: total, isActive: page === total });

  return pages;
}

/**
 * Renders the list of page items (numbers + ellipses) via a render prop.
 * Calculates which pages to show based on page, totalPages, and siblingCount.
 */
export function PaginationItems(props: PaginationItemsProps): JSX.Element {
  const [local] = splitProps(props, ["children"]);
  const ctx = usePaginationContext();
  const items = () => buildItems(ctx.page(), ctx.totalPages(), ctx.siblingCount());
  return <For each={items()}>{(item) => local.children(item)}</For>;
}
