'use client';

import { c as _c } from "react/compiler-runtime";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
import { $getTableColumnIndexFromTableCellNode, $getTableRowIndexFromTableCellNode, $insertTableColumn__EXPERIMENTAL, $insertTableRow__EXPERIMENTAL, $isTableCellNode, $isTableNode, TableNode } from '@lexical/table';
import { $findMatchingParent, mergeRegister } from '@lexical/utils';
import { $getNearestNodeFromDOMNode } from 'lexical';
import { useEffect, useMemo, useRef, useState } from 'react';
import * as React from 'react';
import { createPortal } from 'react-dom';
import { useEditorConfigContext } from '../../../../../lexical/config/client/EditorConfigProvider.js';
import { useDebounce } from '../../utils/useDebounce.js';
const BUTTON_WIDTH_PX = 20;
function TableHoverActionsContainer({
  anchorElem
}) {
  const [editor] = useLexicalComposerContext();
  const editorConfig = useEditorConfigContext();
  const [isShownRow, setShownRow] = useState(false);
  const [isShownColumn, setShownColumn] = useState(false);
  const [shouldListenMouseMove, setShouldListenMouseMove] = useState(false);
  const [position, setPosition] = useState({});
  const tableSetRef = useRef(new Set());
  const tableCellDOMNodeRef = useRef(null);
  const debouncedOnMouseMove = useDebounce(event => {
    const {
      isOutside,
      tableDOMNode
    } = getMouseInfo(event, editorConfig.editorConfig?.lexical);
    if (isOutside) {
      setShownRow(false);
      setShownColumn(false);
      return;
    }
    if (!tableDOMNode) {
      return;
    }
    tableCellDOMNodeRef.current = tableDOMNode;
    let hoveredRowNode = null;
    let hoveredColumnNode = null;
    let tableDOMElement = null;
    editor.update(() => {
      const maybeTableCell = $getNearestNodeFromDOMNode(tableDOMNode);
      if ($isTableCellNode(maybeTableCell)) {
        const table = $findMatchingParent(maybeTableCell, node => $isTableNode(node));
        if (!$isTableNode(table)) {
          return;
        }
        tableDOMElement = editor.getElementByKey(table?.getKey());
        if (tableDOMElement) {
          const rowCount = table.getChildrenSize();
          const colCount =
          // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
          table.getChildAtIndex(0)?.getChildrenSize();
          const rowIndex = $getTableRowIndexFromTableCellNode(maybeTableCell);
          const colIndex = $getTableColumnIndexFromTableCellNode(maybeTableCell);
          if (rowIndex === rowCount - 1) {
            hoveredRowNode = maybeTableCell;
          } else if (colIndex === colCount - 1) {
            hoveredColumnNode = maybeTableCell;
          }
        }
      }
    });
    if (tableDOMElement) {
      const {
        bottom: tableElemBottom,
        height: tableElemHeight,
        left: tableElemLeft,
        right: tableElemRight,
        width: tableElemWidth,
        y: tableElemY
      } = tableDOMElement.getBoundingClientRect();
      const {
        left: editorElemLeft,
        y: editorElemY
      } = anchorElem.getBoundingClientRect();
      if (hoveredRowNode) {
        setShownColumn(false);
        setShownRow(true);
        setPosition({
          height: BUTTON_WIDTH_PX,
          left: tableElemLeft - editorElemLeft,
          top: tableElemBottom - editorElemY + 5,
          width: tableElemWidth
        });
      } else if (hoveredColumnNode) {
        setShownColumn(true);
        setShownRow(false);
        setPosition({
          height: tableElemHeight,
          left: tableElemRight - editorElemLeft + 5,
          top: tableElemY - editorElemY,
          width: BUTTON_WIDTH_PX
        });
      }
    }
  }, 50, 250);
  // Hide the buttons on any table dimensions change to prevent last row cells
  // overlap behind the 'Add Row' button when text entry changes cell height
  const tableResizeObserver = useMemo(() => {
    return new ResizeObserver(() => {
      setShownRow(false);
      setShownColumn(false);
    });
  }, []);
  useEffect(() => {
    if (!shouldListenMouseMove) {
      return;
    }
    document.addEventListener('mousemove', debouncedOnMouseMove);
    return () => {
      setShownRow(false);
      setShownColumn(false);
      document.removeEventListener('mousemove', debouncedOnMouseMove);
    };
  }, [shouldListenMouseMove, debouncedOnMouseMove]);
  useEffect(() => {
    return mergeRegister(editor.registerMutationListener(TableNode, mutations => {
      editor.getEditorState().read(() => {
        for (const [key, type] of mutations) {
          const tableDOMElement_0 = editor.getElementByKey(key);
          switch (type) {
            case 'created':
              tableSetRef.current.add(key);
              setShouldListenMouseMove(tableSetRef.current.size > 0);
              if (tableDOMElement_0) {
                tableResizeObserver.observe(tableDOMElement_0);
              }
              break;
            case 'destroyed':
              tableSetRef.current.delete(key);
              setShouldListenMouseMove(tableSetRef.current.size > 0);
              // Reset resize observers
              tableResizeObserver.disconnect();
              tableSetRef.current.forEach(tableKey => {
                const tableElement = editor.getElementByKey(tableKey);
                if (tableElement) {
                  tableResizeObserver.observe(tableElement);
                }
              });
              break;
            default:
              break;
          }
        }
      });
    }, {
      skipInitialization: false
    }));
  }, [editor, tableResizeObserver]);
  const insertAction = insertRow => {
    editor.update(() => {
      if (tableCellDOMNodeRef.current) {
        const maybeTableNode = $getNearestNodeFromDOMNode(tableCellDOMNodeRef.current);
        maybeTableNode?.selectEnd();
        if (insertRow) {
          $insertTableRow__EXPERIMENTAL();
          setShownRow(false);
        } else {
          $insertTableColumn__EXPERIMENTAL();
          setShownColumn(false);
        }
      }
    });
  };
  if (!editor?.isEditable()) {
    return null;
  }
  return /*#__PURE__*/_jsxs(_Fragment, {
    children: [isShownRow && /*#__PURE__*/_jsx("button", {
      className: editorConfig.editorConfig.lexical.theme.tableAddRows,
      onClick: () => insertAction(true),
      style: {
        ...position
      },
      type: "button"
    }), isShownColumn && /*#__PURE__*/_jsx("button", {
      className: editorConfig.editorConfig.lexical.theme.tableAddColumns,
      onClick: () => insertAction(false),
      style: {
        ...position
      },
      type: "button"
    })]
  });
}
function getMouseInfo(event, editorConfig) {
  const target = event.target;
  if (target && target instanceof HTMLElement) {
    const tableDOMNode = target.closest(`td.${editorConfig.theme.tableCell}, th.${editorConfig.theme.tableCell}`);
    const isOutside = !(tableDOMNode || target.closest(`button.${editorConfig.theme.tableAddRows}`) || target.closest(`button.${editorConfig.theme.tableAddColumns}`) || target.closest(`div.${editorConfig.theme.tableCellResizer}`));
    return {
      isOutside,
      tableDOMNode
    };
  } else {
    return {
      isOutside: true,
      tableDOMNode: null
    };
  }
}
export function TableHoverActionsPlugin(t0) {
  const $ = _c(2);
  const {
    anchorElem: t1
  } = t0;
  const anchorElem = t1 === undefined ? document.body : t1;
  const [editor] = useLexicalComposerContext();
  if (!editor?.isEditable()) {
    return null;
  }
  let t2;
  if ($[0] !== anchorElem) {
    t2 = createPortal(_jsx(TableHoverActionsContainer, {
      anchorElem
    }), anchorElem);
    $[0] = anchorElem;
    $[1] = t2;
  } else {
    t2 = $[1];
  }
  return t2;
}
//# sourceMappingURL=index.js.map