import { flexRender, useReactTable, getCoreRowModel } from '@tanstack/react-table';
import { extendTailwindMerge, twMerge as twMerge$1 } from 'tailwind-merge';
import { omit, get, isEqual } from 'lodash-es';
import { createClassed } from '@tw-classed/react';
import { createClassed as createClassed$1 } from '@tw-classed/core';
import 'clsx';
import createVariatGroupTransfomer from 'tailwind-group-variant';
import * as React from 'react';
import React__default, { forwardRef, useRef, useEffect, useMemo } from 'react';
import { jsx, jsxs } from 'react/jsx-runtime';
import useDimensions from 'react-cool-dimensions';
import * as ScrollAreaPrimitive from '@radix-ui/react-scroll-area';
import AutoSizer from 'react-virtualized-auto-sizer';
import { getByPath as getByPath$1 } from '@clickbar/dot-diver';
import { useVirtualizer } from '@tanstack/react-virtual';
import useMousePosition from '@react-hook/mouse-position';

var __defProp = Object.defineProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var twMerge = extendTailwindMerge({
  classGroups: {
    "font-size": [
      {
        // Fixes incorect merging of text size
        text: ["h1", "h2", "h3", "h4", "h5", "h6"]
      }
    ]
  }
});
var { classed } = createClassed({ merger: twMerge });
createClassed$1({ merger: twMerge });

// src/utils/notEmpty.ts
function notEmpty(value) {
  return value !== null && value !== void 0;
}

// src/utils/classed/expandVariant.ts
createVariatGroupTransfomer({});
function _createCtx(options) {
  const { ignoreNoContextError } = options ?? {};
  const ctx = React__default.createContext(void 0);
  function useContext() {
    const context = React__default.useContext(ctx);
    const noContext = !context;
    if (!ignoreNoContextError && noContext) {
      throw new Error("useContext hook does not have a Provider.");
    }
    return context;
  }
  return {
    useContext,
    Provider: ctx.Provider
  };
}
function createCtx() {
  return _createCtx();
}

// src/components/Table/Table.context.tsx
var { useContext: useTableContext, Provider: TableProvider } = createCtx();
var TableBodyElement = classed("tbody", "w-full h-full dark:divide-white/5 relative");
var TableBody = ({ tablePadding, children, ...props }) => {
  const { paddingTop = 0, paddingBottom = 0 } = tablePadding ?? {};
  return /* @__PURE__ */ jsxs(TableBodyElement, { ...props, children: [
    paddingTop > 0 && /* @__PURE__ */ jsx("tr", { children: /* @__PURE__ */ jsx("td", { style: { height: `${paddingTop}px` } }) }),
    children,
    paddingBottom > 0 && /* @__PURE__ */ jsx("tr", { children: /* @__PURE__ */ jsx("td", { style: { height: `${paddingBottom}px` } }) })
  ] });
};
function renderCell(cell) {
  return flexRender(cell.column.columnDef.cell, cell.getContext());
}
function renderHeader(header) {
  return flexRender(header.column.columnDef.header, header.getContext());
}
function getTableMeta(table) {
  return table.options.meta;
}
var DataRowElement = classed("tr", "border-b border-highlight-ghost", {
  variants: {
    tint: {
      true: "bg-highlight-tint"
    },
    // Used to lightly highlight a row while scrolling
    subtleHover: {
      true: "active:bg-highlight-ghost"
    },
    clickable: {
      true: "cursor-pointer hover:bg-highlight-ghost relative"
    },
    transition: {
      true: "transition-colors delay-75 duration-500 will-change-auto active:transition-none"
    }
  },
  compoundVariants: [{ subtleHover: true, clickable: true, class: "hover:bg-surface-dark/0" }]
});
var Row = React__default.forwardRef(
  ({
    row,
    isScrolling,
    onClick,
    mouseMovedSinceScrollStart,
    mouseMovedSinceScrollEnd,
    hasScrollOffsetSinceMouseMoveDuringScroll,
    ...props
  }, forwardedRef) => {
    const { table } = useTableContext();
    const { onRowClick } = getTableMeta(table) ?? {};
    const isClickable = Boolean(onRowClick) && (!isScrolling || mouseMovedSinceScrollStart && !hasScrollOffsetSinceMouseMoveDuringScroll);
    function handleRowClick(e) {
      if (isClickable) {
        const data = row.original;
        onClick?.(e);
        onRowClick?.(data);
      }
    }
    return /* @__PURE__ */ jsx(
      DataRowElement,
      {
        ref: forwardedRef,
        clickable: isClickable,
        transition: !isScrolling && !mouseMovedSinceScrollEnd,
        onClick: (e) => handleRowClick(e),
        ...props
      }
    );
  }
);
var DataRow = React__default.memo(Row);

// src/components/Table/components/BaseCellElement.tsx
var BaseCellElement = classed("td", "px-24 py-8");
var DataCellElement = classed("td", "relative text-sm font-regular font-body", BaseCellElement);
var DataCell = React__default.memo(
  ({ cell, children, height = "64px", ...props }) => {
    return /* @__PURE__ */ jsxs(DataCellElement, { height, ...props, children: [
      children,
      renderCell(cell)
    ] });
  }
);
var HeaderElement = classed(
  "th",
  BaseCellElement,
  "text-left py-8 pb-14",
  "first:rounded-tl-lg last:rounded-tr-lg",
  "text-sm font-medium  font-body text-content-weak  tracking-wide",
  "relative",
  {
    variants: {},
    defaultVariants: {
      headerBackground: true
    }
  }
);
var HeaderCell = ({ header, style, ...props }) => {
  return /* @__PURE__ */ jsx(
    HeaderElement,
    {
      colSpan: header.colSpan,
      ...props,
      style: { width: header.getSize(), ...style },
      children: header.isPlaceholder ? null : renderHeader(header)
    }
  );
};

// src/components/Table/components/THeaderElement.tsx
var THeaderElement = classed("thead", "sticky top-0 m-0 z-30");
var BaseTableElement = classed(
  "table",
  "table-fixed w-full border-spacing-0 border-collapse relative"
);
var TableElement = ({ ...props }) => {
  return /* @__PURE__ */ jsx(BaseTableElement, { ...props });
};
var TableHeaderBackground = ({
  headerElementRef,
  ...props
}) => {
  const { observe, height } = useDimensions();
  useEffect(() => {
    observe(headerElementRef.current);
  }, [headerElementRef, observe]);
  return /* @__PURE__ */ jsx(TableHeaderBackgroundElement, { ...props, style: { height } });
};
var TableHeaderBackgroundElement = classed(
  "div",
  "absolute -top-px w-full z-20  border-b border-highlight bg-inherit",
  {
    variants: {
      filledHeaderBackground: {
        true: "before-absolute-content before:bg-palette-various-gray-500/10"
      }
    }
  }
);

// src/components/ScrollViewport/ScrollViewport.tsx
var ScrollViewport_exports = {};
__export(ScrollViewport_exports, {
  Container: () => Container,
  FooterSection: () => FooterSection,
  HeaderSection: () => HeaderSection,
  ScrollArea: () => ScrollArea,
  ScrollAreaContainer: () => ScrollAreaContainer,
  ScrollAreaViewport: () => ScrollAreaViewport
});
var ScrollBarElement = classed(
  ScrollAreaPrimitive.ScrollAreaScrollbar,
  "flex touch-none select-none transition-colors relative z-30",
  {
    variants: {
      orientation: {
        vertical: "h-full w-12 border-l border-l-transparent p-[1.5px] animate-slide-left-fade",
        horizontal: "h-8 border-t border-t-transparent p-[1.5px] animate-slide-up-fade"
      }
    },
    defaultVariants: {
      orientation: "vertical"
    }
  }
);
var ScrolllBarThumbElement = classed(
  ScrollAreaPrimitive.ScrollAreaThumb,
  "bg-content-ghost relative flex-1 rounded-full overflow-hidden backdrop-contrast-100 min-h-[44px] transition-[height] will-change-[height]"
);
var ScrollBar = React.forwardRef(({ className, orientation = "vertical", ...props }, ref) => /* @__PURE__ */ jsx(ScrollBarElement, { ref, orientation, ...props, children: /* @__PURE__ */ jsx(ScrolllBarThumbElement, {}) }));
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName;

// src/utils/environment-utils.ts
function isDevelopment() {
  if (typeof window === "undefined" && typeof process !== "undefined" && process.env.NODE_ENV === "development") {
    return true;
  }
  if (typeof window !== "undefined" && (window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1")) {
    return true;
  }
  return false;
}
function getByPath(object, path, _maxDepth) {
  return getByPath$1(object, path);
}

// src/utils/objectMap.ts
function objectMap(obj, fn) {
  return Object.fromEntries(
    Object.entries(obj).map(([k, v], index) => fn({ key: k, value: v, index, get: getByPath })).filter(notEmpty)
  );
}

// src/utils/pickProps.ts
var NO_DEFAULT_VALUE = "_pick_";
function pickProps(props, pickedProps, options) {
  const { shouldValidatePickProp = true } = options ?? {};
  const entries = Object.entries(pickedProps).map(([path, defaultValue]) => {
    const prop = get(props, path);
    if (defaultValue === NO_DEFAULT_VALUE) {
      return [path, prop];
    }
    if (shouldValidatePickProp) {
      validatePickProp(defaultValue, pickedProps);
    }
    return [path, prop ?? defaultValue];
  });
  return Object.fromEntries(entries);
}
function validatePickProp(input, pickedProps) {
  if (isDevelopment()) {
    const startsWith = ["_p", "pick"];
    const isLikelyTypo = typeof input === "string" && startsWith.some((typo) => input.startsWith(typo));
    if (isLikelyTypo) {
      const functionName = "`pickProps`";
      throw new Error(`
      Error thrown from ${functionName}
      
      A possible typo was detected in the arguments passed to the ${functionName} function.

      Expected value: "${NO_DEFAULT_VALUE}"

      Received value: "${input}" \u274C

      ${JSON.stringify(
        objectMap(pickedProps, ({ key, value }) => [
          key,
          value === input ? `${value} \u274C` : value
        ]),
        null,
        2
      )}
 
      If this is intended, add \`shouldValidatePickProp: true\` to the options.

      Note: This error is thrown only during development.

      `);
    }
  }
}
var ScrollAreaContainer = ({
  scrollAreaClassName,
  autoSizerClassName,
  ...props
}) => {
  const scrollAreaProps = pickProps(props, {
    asChild: "_pick_",
    dir: "_pick_",
    scrollHideDelay: "_pick_",
    type: "_pick_"
  });
  const autoSizerProps = pickProps(props, {
    defaultHeight: "_pick_",
    defaultWidth: "_pick_",
    disableHeight: "_pick_",
    disableWidth: "_pick_"
  });
  const { children, className, ...rest } = omit(props, [
    ...Object.keys(scrollAreaProps),
    ...Object.keys(autoSizerProps)
  ]);
  return /* @__PURE__ */ jsx(ScrollAreaContainerElement, { className, ...rest, children: /* @__PURE__ */ jsx(
    AutoSizer,
    {
      className: twMerge$1(
        "bg-inherit rounded-[inherit] rounded-b-[inherit] rounded-t-[inherit]",
        autoSizerClassName
      ),
      ...autoSizerProps,
      children: ({ width, height }) => /* @__PURE__ */ jsxs(
        ScrollAreaPrimitive.Root,
        {
          className: twMerge$1("bg-inherit", scrollAreaClassName),
          ...scrollAreaProps,
          style: { width, height, overflow: "hidden" },
          children: [
            children,
            /* @__PURE__ */ jsx(ScrollBar, {}),
            /* @__PURE__ */ jsx(ScrollAreaPrimitive.Corner, {})
          ]
        }
      )
    }
  ) });
};
var ScrollAreaContainerElement = classed("div", "w-full  bg-inherit", {
  variants: {
    grow: {
      true: "!grow",
      false: "!grow"
    }
  },
  defaultVariants: {
    grow: true
  }
});
var ScrollArea = forwardRef(
  ({ children, ...props }, forwardedRef) => {
    return /* @__PURE__ */ jsxs(ScrollAreaPrimitive.Root, { ...props, className: "overflow-hidden grow", children: [
      /* @__PURE__ */ jsx(ScrollAreaPrimitive.Viewport, { className: "h-full w-full", ref: forwardedRef, children }),
      /* @__PURE__ */ jsx(ScrollBar, {})
    ] });
  }
);
var ScrollAreaViewport = classed(ScrollAreaPrimitive.Viewport, "w-full h-full");
var Container = classed("div", "grow flex flex-col");
var HeaderSection = classed("div", "shrink-0");
var FooterSection = classed("div", "shrink-0");
function useScrollingData({
  isScrolling,
  scrollOffset
}) {
  const prevMousePositionSinceScrollStart = useRef();
  const prevMousePositionSinceScrollEnd = useRef();
  const mouseData = useMousePosition(document.body, { fps: 20 });
  const mousePosition = useMemo(() => {
    return { x: mouseData.x, y: mouseData.y };
  }, [mouseData.x, mouseData.y]);
  const mousePositionAtScrollStart = useRef();
  const mousePositionAtScrollEnd = useRef();
  useEffect(() => {
    if (isScrolling && !mousePositionAtScrollStart.current) {
      mousePositionAtScrollStart.current = mousePosition;
    }
    if (!isScrolling && mousePositionAtScrollStart.current) {
      mousePositionAtScrollStart.current = void 0;
    }
    if (isScrolling) {
      prevMousePositionSinceScrollStart.current = mousePosition;
    } else {
      prevMousePositionSinceScrollStart.current = void 0;
    }
    if (!isScrolling && !mousePositionAtScrollEnd.current) {
      mousePositionAtScrollEnd.current = mousePosition;
    }
    if (isScrolling && mousePositionAtScrollEnd.current) {
      mousePositionAtScrollEnd.current = void 0;
    }
    if (!isScrolling) {
      prevMousePositionSinceScrollEnd.current = mousePosition;
    } else {
      prevMousePositionSinceScrollEnd.current = void 0;
    }
  }, [isScrolling, mousePosition, scrollOffset]);
  const mouseMovedSinceScrollStart = !isEqual(
    mousePositionAtScrollStart.current,
    prevMousePositionSinceScrollStart.current
  );
  const mouseMovedSinceScrollEnd = !isEqual(
    mousePositionAtScrollEnd.current,
    prevMousePositionSinceScrollEnd.current
  );
  const scrollOffsetSinceMouseMoveDuringScroll = useRef();
  useEffect(() => {
    if (isScrolling && mouseMovedSinceScrollStart) {
      scrollOffsetSinceMouseMoveDuringScroll.current = scrollOffset;
    } else {
      scrollOffsetSinceMouseMoveDuringScroll.current = void 0;
    }
  }, [isScrolling, mouseMovedSinceScrollStart, scrollOffset]);
  const hasScrollOffsetSinceMouseMoveDuringScroll = Boolean(scrollOffsetSinceMouseMoveDuringScroll.current) && scrollOffset !== scrollOffsetSinceMouseMoveDuringScroll.current;
  return {
    isScrolling,
    hasScrollOffsetSinceMouseMoveDuringScroll,
    mouseMovedSinceScrollStart,
    mouseMovedSinceScrollEnd
  };
}
function useTableVirtualizer({ rows }) {
  const tableContainerRef = useRef(null);
  const virtualizer = useVirtualizer({
    count: rows.length,
    getScrollElement: () => tableContainerRef.current,
    overscan: 10,
    estimateSize: () => 50
  });
  const scrollData = useScrollingData(virtualizer);
  return {
    virtualizer,
    tableContainerRef,
    getTablePadding,
    ...scrollData
  };
}
function getTablePadding(virtualizer) {
  const { getVirtualItems, getTotalSize } = virtualizer;
  const virtualRows = getVirtualItems();
  const totalSize = getTotalSize();
  if (virtualRows.length > 0) {
    const firstVirtualRow = virtualRows[0];
    const lastVirtualRow = virtualRows[virtualRows.length - 1];
    return {
      paddingTop: firstVirtualRow?.start ?? 0,
      paddingBottom: totalSize - (lastVirtualRow?.end ?? 0)
    };
  }
  return {
    paddingTop: 0,
    paddingBottom: 0
  };
}
var useTable = ({ data, columns, meta }) => {
  const table = useReactTable({
    data,
    columns,
    meta,
    enableColumnResizing: true,
    getCoreRowModel: getCoreRowModel()
  });
  return table;
};
var HeaderRowElement = classed("tr");
function getTableMetaProps({ onRowClick }) {
  return { onRowClick };
}
var Table = ({
  className,
  zebraRows,
  filledHeaderBackground,
  height,
  ...props
}) => {
  const meta = getTableMetaProps(props);
  const table = useTable({ ...props, meta });
  const { rows } = table.getRowModel();
  const {
    tableContainerRef,
    virtualizer,
    getTablePadding: getTablePadding2,
    isScrolling,
    mouseMovedSinceScrollStart,
    mouseMovedSinceScrollEnd,
    hasScrollOffsetSinceMouseMoveDuringScroll
  } = useTableVirtualizer({
    rows
  });
  const ctx = {
    table
  };
  const headerElementRef = useRef(null);
  return /* @__PURE__ */ jsx(TableProvider, { value: ctx, children: /* @__PURE__ */ jsxs(ScrollViewport_exports.Container, { className: twMerge$1("bg-surface", className), children: [
    /* @__PURE__ */ jsx(ScrollViewport_exports.HeaderSection, { className: "h-40", children: " " }),
    /* @__PURE__ */ jsxs(ScrollViewport_exports.ScrollAreaContainer, { className: "bg-inherit", children: [
      /* @__PURE__ */ jsx(TableHeaderBackground, { headerElementRef }),
      /* @__PURE__ */ jsx(ScrollViewport_exports.ScrollAreaViewport, { ref: tableContainerRef, children: /* @__PURE__ */ jsxs(TableElement, { children: [
        /* @__PURE__ */ jsx(THeaderElement, { className: "z-30", ref: headerElementRef, children: table.getHeaderGroups().map((headerGroup) => /* @__PURE__ */ jsx(HeaderRowElement, { children: headerGroup.headers.map((header) => /* @__PURE__ */ jsx(HeaderCell, { header }, header.id)) }, headerGroup.id)) }),
        /* @__PURE__ */ jsx(TableBody, { tablePadding: getTablePadding2(virtualizer), children: virtualizer.getVirtualItems().map((virtualRow) => {
          const row = rows[virtualRow.index];
          return /* @__PURE__ */ jsx(
            DataRow,
            {
              row,
              ref: virtualizer.measureElement,
              "data-index": virtualRow.index,
              tint: zebraRows && virtualRow.index % 2 !== 0,
              isScrolling,
              mouseMovedSinceScrollStart,
              mouseMovedSinceScrollEnd,
              hasScrollOffsetSinceMouseMoveDuringScroll,
              children: row.getVisibleCells().map((cell) => /* @__PURE__ */ jsx(DataCell, { cell, height: "50px" }, cell.id))
            },
            row.id
          );
        }) })
      ] }) })
    ] })
  ] }) });
};

export { Table, useTable };
//# sourceMappingURL=out.js.map
//# sourceMappingURL=index.js.map