(function () {
    const EDGE_SIZE = 7;
    const MIN_COL_WIDTH = 28;
    const MIN_ROW_HEIGHT = 24;

    function closestEditableCell(target, editor) {
        const cell = target && target.closest ? target.closest('td, th') : null;
        return cell && editor.contains(cell) ? cell : null;
    }

    function getResizeMode(event, cell) {
        if (!cell) return '';
        const rect = cell.getBoundingClientRect();
        const nearRight = rect.right - event.clientX <= EDGE_SIZE;
        const nearBottom = rect.bottom - event.clientY <= EDGE_SIZE;
        if (nearRight && event.clientX >= rect.left) return 'col';
        if (nearBottom && event.clientY >= rect.top) return 'row';
        return '';
    }

    function getColumnCells(table, columnIndex) {
        return Array.from(table.rows)
            .map(row => row.cells[columnIndex])
            .filter(Boolean);
    }

    function setColumnWidth(table, columnIndex, width) {
        const safeWidth = Math.max(MIN_COL_WIDTH, Math.round(width));
        getColumnCells(table, columnIndex).forEach(cell => {
            cell.style.width = safeWidth + 'px';
            cell.style.minWidth = MIN_COL_WIDTH + 'px';
        });
    }

    function setRowHeight(row, height) {
        const safeHeight = Math.max(MIN_ROW_HEIGHT, Math.round(height));
        row.style.height = safeHeight + 'px';
        Array.from(row.cells).forEach(cell => {
            cell.style.height = safeHeight + 'px';
            cell.style.minHeight = MIN_ROW_HEIGHT + 'px';
        });
    }

    function triggerResizeEnd(editor, options) {
        if (options && typeof options.onResizeEnd === 'function') {
            options.onResizeEnd(editor);
        }
    }

    window.attachResizableEditorTables = function attachResizableEditorTables(editor, options) {
        if (!editor || editor.__resizableTablesAttached) return;
        editor.__resizableTablesAttached = true;

        let activeResize = null;

        editor.addEventListener('mousemove', event => {
            if (activeResize) return;
            const cell = closestEditableCell(event.target, editor);
            const mode = getResizeMode(event, cell);
            editor.style.cursor = mode === 'col' ? 'col-resize' : mode === 'row' ? 'row-resize' : '';
        });

        editor.addEventListener('mouseleave', () => {
            if (!activeResize) editor.style.cursor = '';
        });

        editor.addEventListener('mousedown', event => {
            if (event.button !== 0) return;
            const cell = closestEditableCell(event.target, editor);
            const mode = getResizeMode(event, cell);
            if (!mode) return;

            const table = cell.closest('table');
            const row = cell.closest('tr');
            if (!table || !row) return;

            event.preventDefault();
            const tableRect = table.getBoundingClientRect();
            table.style.width = Math.round(tableRect.width) + 'px';

            activeResize = {
                mode,
                table,
                row,
                columnIndex: cell.cellIndex,
                startX: event.clientX,
                startY: event.clientY,
                startWidth: cell.getBoundingClientRect().width,
                startHeight: row.getBoundingClientRect().height
            };

            document.body.classList.add('editor-table-is-resizing');
            editor.style.cursor = mode === 'col' ? 'col-resize' : 'row-resize';
        });

        document.addEventListener('mousemove', event => {
            if (!activeResize) return;
            event.preventDefault();

            if (activeResize.mode === 'col') {
                setColumnWidth(
                    activeResize.table,
                    activeResize.columnIndex,
                    activeResize.startWidth + (event.clientX - activeResize.startX)
                );
            } else {
                setRowHeight(
                    activeResize.row,
                    activeResize.startHeight + (event.clientY - activeResize.startY)
                );
            }
        });

        document.addEventListener('mouseup', () => {
            if (!activeResize) return;
            const resizeEditor = editor;
            activeResize = null;
            document.body.classList.remove('editor-table-is-resizing');
            resizeEditor.style.cursor = '';
            triggerResizeEnd(resizeEditor, options || {});
        });
    };
})();
