'use client';
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { ApplicationRowActions } from './application-row-actions.js';
/**
 * Manages React portals for ApplicationRowActions into Tabulator's action column cells
 * for application rows (identified via the [data-application-id] portal target).
 */
export function ApplicationRowActionsManager({ tableContainer, renderTick, rows, }) {
    const [portalContainers, setPortalContainers] = useState(new Map());
    useEffect(() => {
        if (!tableContainer) {
            setPortalContainers(new Map());
            return;
        }
        const elements = tableContainer.querySelectorAll('[data-application-id]');
        const nextMap = new Map();
        elements.forEach((el) => {
            const id = el.getAttribute('data-application-id');
            if (id)
                nextMap.set(id, el);
        });
        setPortalContainers((prev) => {
            if (prev.size !== nextMap.size)
                return nextMap;
            for (const [id, el] of nextMap) {
                if (prev.get(id) !== el)
                    return nextMap;
            }
            return prev;
        });
    }, [tableContainer, renderTick]);
    const appById = new Map();
    function collect(input) {
        for (const row of input) {
            if (row._isApplication && row._applicationId) {
                appById.set(row._applicationId, row);
            }
            if (row._children)
                collect(row._children);
        }
    }
    collect(rows);
    const portals = [];
    for (const [appId, container] of portalContainers) {
        const row = appById.get(appId);
        if (!row)
            continue;
        portals.push(createPortal(_jsx(ApplicationRowActions, { applicationId: appId, applicationName: row.name, repositoryPath: row._repositoryPath ?? '', cloudUrl: row._applicationCloudUrl }), container, appId));
    }
    if (portals.length === 0)
        return null;
    return (_jsxs(_Fragment, { children: [null, portals] }));
}
