import React, {FC, ReactNode, useLayoutEffect, useRef, useState} from "react";
import {colors} from "./tree/Colors";
import {Handle} from "./tree/Handle";
import {Handle as ReactFlowHandle, NodeProps, Position} from "@xyflow/react";
import {RenderedNodeDataInBranch, TestablePartial, useNodesStore} from "./tree/store";
import {motion} from 'motion/react';
import classNames from "classnames";
import {getNodesFinder} from "./tree/NodesFinder";
import {StateBranchNode} from "./tree/StateBranchNode";
import {request} from "./tree/Color";
import {__, CouponsPlus} from "./globals";
import {EmulatedButton} from "./tree/EmulatedButton";
import {useOpenTestablesPopupWindow} from "./tree/useOpenTestablesPopupWindow";
import {getOpenPopupsCount} from "./tree/hooks";
import {cloneDeep, merge} from "lodash";
import {getPopupStackDimensionCalculators} from "./tree/ulitilies";
import {getOffersPopupWindowContext} from "./OffersBranch";
import {incompatibleOffersFromInsideTiers} from "./tree/actions/SelectOffersNew";
import {NonImplementedMessage} from "./tree/actions/NonImplementedMessage";
import {PopupWindowStateContext, ProUpgradePopupWindowIsOpen, TreeContextData} from "./tree/atoms";
import {ComponentMeta, getComponentMeta, getComponentMetaData} from "./tree/ComponentsMeta";
import {generateIdForType} from "./tree/NodeHelpers";
import {equals, TierType} from "./tree/tiers";
import {AmountValidatorOptions} from "./tree/cards/filterinterfaces";
import {pickByPaths} from "./tree/actions/SelectTierNew";
import {Button} from "./tree/cards/Button";
import {SuggestedArrow} from "./tree/SuggestedArrow";
import {useSuggestedScopeForTestableId} from "./tree/getSuggestedScopeForTestable";
import {ComponentCategory} from "./tree/components";
import {FloatingMarker} from "./tree/FloatingMarker";
import {DiscountMeta} from "./tree/cards/Discount";
import {useSetAtom} from "jotai";

export type SelectActionSplitNodeData = RenderedNodeDataInBranch & {
    renderedNodeType: 'action-split',
}

type ActionButtonProps = {
    label: string;
    icon: React.ReactNode;
    onClick: () => void;
    color: typeof colors.blue,
    inversedColor?: boolean
}

const ActionButton: FC<ActionButtonProps> = ({label, icon, onClick, color, inversedColor}) => {
    return (
        <EmulatedButton
            className={`flex items-center space-x-2 ${request(color).background(inversedColor? 20 : 100)} text-base font-semibold ${request(color).text(inversedColor? 50 : 10)} rounded-full px-3 py-1 transition-all hover:scale-105 active:scale-100 border-px border-opacity-40 ${color === colors.blue ? 'border-blue-shade-200' : ''}`}
            onClickCapture={onClick}
        >
            <div className={`flex items-center justify-center min-h-4 min-w-4 ${request(color).background(inversedColor? 40 : 10)} rounded-5`}>
                {icon}
            </div>
            <span>{label}</span>
        </EmulatedButton>
    );
}

let offersTestableisOpen = false;
let tiertestableisOpen = false;
const tierIsNotImplemented = CouponsPlus.implementations.branches.tiered === false

const getDefaultOptionsForFirstTierSubchild = (meta: ComponentMeta): Record<any, any> => {
    const tiertype = meta?.tierType || TierType.Numeric
    let options: Record<any, any> = cloneDeep(getComponentMetaData(meta).defaultOptions) || {}

    if (meta?.tierDefaultOptions?.first) {
        options = meta.tierDefaultOptions.first()
    } else if (tiertype === TierType.Numeric) {
        // as a self-invoking anonymous function to create a new instance each time
        options = (() => ({
                quantity: equals(1)
            }) as AmountValidatorOptions
        )()
    }

    return pickByPaths(options, meta.tierFields || [])

}

const filteredItemsLabel =                             <span className={classNames('inline-flex items-center space-x-1 font-semibold px-1 leading-4 rounded-6  bg-opacity-40 text-smaller-2', {
    'bg-purple-tint-20 text-purple-tint-70': true,
})}>{<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="currentColor"
          className="min-w-[10px] min-h-[10px] max-w-[10px] max-h-[10px]">
    <path
        d="M7.628 1.099a.75.75 0 0 1 .744 0l5.25 3a.75.75 0 0 1 0 1.302l-5.25 3a.75.75 0 0 1-.744 0l-5.25-3a.75.75 0 0 1 0-1.302l5.25-3Z"/>
    <path
        d="m2.57 7.24-.192.11a.75.75 0 0 0 0 1.302l5.25 3a.75.75 0 0 0 .744 0l5.25-3a.75.75 0 0 0 0-1.303l-.192-.11-4.314 2.465a2.25 2.25 0 0 1-2.232 0L2.57 7.239Z"/>
    <path
        d="m2.378 10.6.192-.11 4.314 2.464a2.25 2.25 0 0 0 2.232 0l4.314-2.465.192.11a.75.75 0 0 1 0 1.303l-5.25 3a.75.75 0 0 1-.744 0l-5.25-3a.75.75 0 0 1 0-1.303Z"/>
</svg>}<span>{__('Filtered items')}</span>{<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"
                                                fill="currentColor"
                                                className="min-w-[10px] min-h-[10px] max-w-[10px] max-h-[10px]">
    <path fillRule="evenodd"
          d="M2 13.25a.75.75 0 0 1 .75-.75h6.5V4.56l-.97.97a.75.75 0 0 1-1.06-1.06l2.25-2.25a.75.75 0 0 1 1.06 0l2.25 2.25a.75.75 0 0 1-1.06 1.06l-.97-.97v8.69A.75.75 0 0 1 10 14H2.75a.75.75 0 0 1-.75-.75Z"
          clipRule="evenodd"/>
</svg>
}</span>

const getAddOfferDescription = (suggestedScope: string | undefined): ReactNode => {
    if (suggestedScope === 'bogo') {
        return<>
            {__('Add a BOGO offer that uses the *').replace('*', '')}
            {filteredItemsLabel}
            {__('as the "buy" items')}
        </>
    } else if (suggestedScope === 'item_discounts') {
        return <>
            {__('Add a Discount offer that applies discounts to the *').replace('*', '')}
            {filteredItemsLabel}
        </>
    } else if (suggestedScope === 'cart_discounts') {
        return <>
            {__('Add a Discount offer that uses the *').replace('*', '')}
            {filteredItemsLabel}
            {__('as a condition for the cart discount')}
        </>
    }

    return <>
        {__('Add an offer using the *').replace('*', '')}
        {filteredItemsLabel}
    </>
};
export const SelectActionSplitBranch: FC<{ data: SelectActionSplitNodeData } & NodeProps> = ({id}) => {
    const nodesFinder = getNodesFinder();
    const branch = nodesFinder.get<StateBranchNode>(id);

    /**
     * NOTE: BECAUSE OF SWAPPING AND RE-RENDERING: BRANCH HERE MIGHT BE UNDEFINED UPON CHANGING THE BRANCH, SO CONSIDER BRANCH POSSIBLY UNDEFINED
     */

    const isInsideBranch = branch?.isInsideAnotherBranch();

    const openTestablesPopup = useOpenTestablesPopupWindow()
    const setIsProUpgradePopupOpen = useSetAtom(ProUpgradePopupWindowIsOpen)
    /*
    const openExamplesPopup = useOpenExamplesPopupWindow()
*/
    const addBranchOffer = useNodesStore(store => store.addBranchOffer)

    const splitContainerRef = useRef<HTMLDivElement | null>(null);
    const offerButtonRef = useRef<HTMLDivElement | null>(null);
    const tierButtonRef = useRef<HTMLDivElement | null>(null);
    const [splitPaths, setSplitPaths] = useState<{
        width: number;
        height: number;
        centerX: number;
        centerY: number;
        leftX: number;
        leftY: number;
        rightX: number;
        rightY: number;
    } | null>(null);

    const handleAddOffer = () => {
        if (offersTestableisOpen ) {
            return
        }

        offersTestableisOpen = true
        // @ts-ignore
        openTestablesPopup({
            // @ts-ignore
            context: merge(
                {

                    data: getPopupStackDimensionCalculators( getOpenPopupsCount())
                },
                {
                    data: {
                        showTabs: false,
                        extraData: {
                            suggestedScope,
                        },
                        suggested: {
                            bogo: {
                                type: 'category',
                                id: ComponentCategory.BOGO
                            },
                            item_discounts: {
                                type: 'component',
                                id: DiscountMeta.id
                            },
                            cart_discounts: {
                                type: 'component',
                                id: DiscountMeta.id
                            }
                        }[suggestedScope!]
                    } as Partial<TreeContextData>
                },
                getOffersPopupWindowContext([
                    // exclude get x if innside another branch (aka in tiers) bc get x is not supported in tiers currently
                    ...(branch?.isInsideAnotherBranch() ? incompatibleOffersFromInsideTiers : [])
                ])
            ),
            onClose: (data) => {
                const {status, components} = data

                if (status === 'success' && components?.length > 0) {
                    // let's js ad the offer to the branch, the grove will handle the necessary logic for converting the branch if necessary, adding the offer to the store, etc.
                    addBranchOffer(components[0], branch!.data.id)
                    close()
                } else {
                }
                offersTestableisOpen = false
                /*// @ts-ignore
                const saver = new TestablesSaver(context)
                // @ts-ignore
                saver.add(data.components)*/
            }
        })
        return
        // alight so here we'll open the testables popup window set to offers
        // then we'll add a handler so that we can talk to it after its been closed
        // there are two possible outcomes after closing:
        // 1- offers have been seected
        // 2- no offers have been selected, the user quit the popup

        // lets just first open it
        // @ts-ignore
        /*const context = {
            id: 'offers-new',
            scope: 'tree-node',
            data: {
                componentType: 'filter',
                targetType: 'root', // root | testableComposite
                targetId: null, // string id if testableComposite, index if root (eg: 0 for the first root, 1 for the second root, etc)
            }
        } as PopupWindowStateContext<TreeContextData>*/

        /*openTestablesPopup({
            // @ts-ignore
            context,
            onClose: (data) => {
                console.log('got a request to close the popup wit: ', data)
                /!*!// @ts-ignore
                const saver = new TestablesSaver(context)
                // @ts-ignore
                saver.add(data.components)*!/
            }
        })*/
        /**
         * const openNewTestablesPopupWindow = useNewTestablesPopupWindow({
         *     onClose: () => {} // here we'll handle the offers that were selected
         * })
         *
         * opennewNewTestablesPopupWindow({
         *      //here we'll set the data for the popup window (context, etc.)
         * })
         */

    };

    const handleAddTier = () => {
        if (tiertestableisOpen) {
            return
        }

        if (tierIsNotImplemented) {
            setIsProUpgradePopupOpen({
                isOpen: true,
                title: __('Create Bulk and Tiered Offers with Pro'),
            })
            return
        }
        //const addBranchOffer = useNodesStore(store => store.addBranchOffer)
        // @ts-ignore
        const context = {
            id: 'tier-new',
            scope: 'tier-base',
            data: {
                supportedComponentTypes: ['filter', 'condition'],
                componentType: 'filter',
                targetType: 'testableComposite', //
                supportsOptionalQuantity: false,
                supportsMultipleComponents: false,
                targetId: branch!.data.id, // string id if testableComposite, index if root (eg: 0 for the first root, 1 for the second root, etc.)
                mainWindow: {
                    title: __('What will the tiers be based on?'),
                    description: '',
                },
                ...getPopupStackDimensionCalculators(getOpenPopupsCount())
            }
        } as PopupWindowStateContext<TreeContextData>;

        tiertestableisOpen = true
        // we need: component type: filter, condition, etc
        openTestablesPopup({
            // @ts-ignore
            context,

            onClose: (data) => {
                const {addTreeNode} = useNodesStore.getState()
                const {status, components, componentType} = data
                const meta = getComponentMeta(`${componentType}s`, components?.[0]?.type)
                // code is repeated from select-offers, should ideally be refactored to remove duplication
                if (status === 'success' && components?.length > 0) {
                    const baseTestableId = generateIdForType('testable');

                    addTreeNode(
                        {
                            parentBranchTestableId: baseTestableId,
                            testable: {
                                id: generateIdForType('testable.partial'),
                                options: getDefaultOptionsForFirstTierSubchild(meta!)
                            } as Omit<TestablePartial<Record<any, any>>, 'id'>,
                            branch: {
                                id: generateIdForType('branch'),
                                type: 'select-action',
                                children: []
                            }
                        },
                        {
                            parentBranchId: branch!.data.id,
                            newTieredBranchData: {
                                baseTestable: {
                                    ...components[0]!,
                                    testableType: componentType as 'filter' | 'condition'
                                },
                                tierType: meta?.tierType || TierType.Numeric,
                            }
                        }
                    )

                } else {
                }
                setTimeout(() => {
                    tiertestableisOpen = false
                }, 500)
            }
        })
        return
    };

    const addIcon = (
        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={2}
             stroke="currentColor" className={colors.blue.text(100)}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M12 4.5v15m7.5-7.5h-15"/>
        </svg>
    );

    const tierIcon = (
        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"
             className="text-gray-100 rotate-180 min-w-3 min-h-3 max-w-3 max-h-3">
            <path stroke-linecap="round" stroke-linejoin="round" d="M9 15 3 9m0 0 6-6M3 9h12a6 6 0 0 1 0 12h-3"/>
        </svg>
    );

    const buttonAnchorHandleStyle: React.CSSProperties = {
        left: '50%',
        top: 0,
        right: 'auto',
        bottom: 'auto'
    };

    const splitLineColor = request(colors.blue).text(100);
    const splitStartOffset = 0;
    const splitMinVertical = 1;
    const splitDiagonalLength = 72;
    const splitLabelRadius = 10;

    const leftSplitY = splitPaths ? Math.max(splitStartOffset + splitMinVertical, splitPaths.leftY - splitDiagonalLength) : 0;
    const rightSplitY = splitPaths ? Math.max(splitStartOffset + splitMinVertical, splitPaths.rightY - splitDiagonalLength) : 0;
    const leftControlY = splitPaths ? Math.max(splitStartOffset + splitMinVertical + 4, splitPaths.leftY - splitDiagonalLength / 2) : 0;
    const rightControlY = splitPaths ? Math.max(splitStartOffset + splitMinVertical + 4, splitPaths.rightY - splitDiagonalLength / 2) : 0;
    const labelT = 0.72;
    const leftControlX = splitPaths ? splitPaths.centerX : 0;
    const rightControlX = splitPaths ? splitPaths.centerX : 0;
    const leftLabelX = splitPaths
        ? ((1 - labelT) ** 2) * splitPaths.centerX + 2 * (1 - labelT) * labelT * leftControlX + (labelT ** 2) * splitPaths.leftX
        : 0;
    const leftLabelY = splitPaths
        ? ((1 - labelT) ** 2) * leftSplitY + 2 * (1 - labelT) * labelT * leftControlY + (labelT ** 2) * splitPaths.leftY
        : 0;
    const rightLabelX = splitPaths
        ? ((1 - labelT) ** 2) * splitPaths.centerX + 2 * (1 - labelT) * labelT * rightControlX + (labelT ** 2) * splitPaths.rightX
        : 0;
    const rightLabelY = splitPaths
        ? ((1 - labelT) ** 2) * rightSplitY + 2 * (1 - labelT) * labelT * rightControlY + (labelT ** 2) * splitPaths.rightY
        : 0;

    useLayoutEffect(() => {
        if (!splitContainerRef.current || !offerButtonRef.current || !tierButtonRef.current) {
            return;
        }

        const containerRect = splitContainerRef.current.getBoundingClientRect();
        const offerRect = offerButtonRef.current.getBoundingClientRect();
        const tierRect = tierButtonRef.current.getBoundingClientRect();

        const leftX = offerRect.left - containerRect.left + offerRect.width / 2;
        const rightX = tierRect.left - containerRect.left + tierRect.width / 2;
        const leftY = offerRect.top - containerRect.top;
        const rightY = tierRect.top - containerRect.top;

        setSplitPaths({
            width: containerRect.width,
            height: containerRect.height,
            centerX: containerRect.width / 2,
            centerY: containerRect.height / 2,
            leftX,
            leftY,
            rightX,
            rightY,
        });
    }, [isInsideBranch]);

    const suggestedScope = useSuggestedScopeForTestableId(branch?.testableNode.getId() || '')

    // Vertical layout (when NOT inside another branch)
    const verticalSplitContent = (
        <div className="relative flex flex-col items-start pt-8" ref={splitContainerRef}>
            {suggestedScope === 'bogo' && <FloatingMarker prefix={__('BOGO')} label={__('Get')} />}
            {/* The inverted Y SVG lines that branch out to the two buttons */}
            {splitPaths && (
                <svg
                    width={splitPaths.width}
                    height={splitPaths.height}
                    viewBox={`0 0 ${splitPaths.width} ${splitPaths.height}`}
                    className={`pointer-events-none absolute inset-0 ${splitLineColor}`}
                >
                    <path
                        d={`M ${splitPaths.centerX} ${splitStartOffset} L ${splitPaths.centerX} ${Math.max(splitStartOffset + splitMinVertical, splitPaths.leftY - splitDiagonalLength)} Q ${splitPaths.centerX} ${Math.max(splitStartOffset + splitMinVertical + 4, splitPaths.leftY - splitDiagonalLength / 2)} ${splitPaths.leftX} ${splitPaths.leftY}`}
                        stroke="currentColor"
                        strokeWidth="2"
                        fill="none"
                        strokeLinecap="round"
                    />
                    <path
                        d={`M ${splitPaths.centerX} ${splitStartOffset} L ${splitPaths.centerX} ${Math.max(splitStartOffset + splitMinVertical, splitPaths.rightY - splitDiagonalLength)} Q ${splitPaths.centerX} ${Math.max(splitStartOffset + splitMinVertical + 4, splitPaths.rightY - splitDiagonalLength / 2)} ${splitPaths.rightX} ${splitPaths.rightY}`}
                        stroke="currentColor"
                        strokeWidth="2"
                        fill="none"
                        strokeLinecap="round"
                    />
                    <circle
                        cx={leftLabelX}
                        cy={leftLabelY}
                        r={splitLabelRadius}
                        fill="currentColor"
                        stroke="white"
                        strokeWidth="2"
                    />
                    <text
                        x={leftLabelX}
                        y={leftLabelY}
                        textAnchor="middle"
                        dominantBaseline="central"
                        className="fill-[white] text-[10px] font-semibold"
                    >
                        A
                    </text>
                    <circle
                        cx={rightLabelX}
                        cy={rightLabelY}
                        r={splitLabelRadius}
                        fill="currentColor"
                        stroke="white"
                        strokeWidth="2"
                    />
                    <text
                        x={rightLabelX}
                        y={rightLabelY}
                        textAnchor="middle"
                        dominantBaseline="central"
                        className="fill-[white] text-[10px] font-semibold"
                    >
                        B
                    </text>
                </svg>
            )}

            {/* Two action buttons side by side */}
            <div className="flex items-start space-x-4 mt-20">
                <div className="relative flex items-center justify-center" ref={offerButtonRef}>
                    <ReactFlowHandle
                        id="offer"
                        type="source"
                        position={Position.Bottom}
                        className="opacity-0"
                        style={buttonAnchorHandleStyle}
                    />
                    <div className="inline-flex flex-col items-start gap-2 w-fit">
                        <SuggestedArrow show={['bogo', 'item_discounts', 'cart_discounts'].includes(suggestedScope!)} label={{
                            'bogo': __('Add BOGO Offer'),
                            'item_discounts': __('Add Discount Offer'),
                            'cart_discounts': __('Add Discount Offer'),
                        }[suggestedScope!]}>
                            <ActionButton
                                label={__('Add Offer')}
                                icon={addIcon}
                                onClick={handleAddOffer}
                                color={colors.blue}
                            />
                        </SuggestedArrow>
                        <p className="max-w-29 text-smaller-1 text-gray-500 leading-[14px]">
                            {getAddOfferDescription(suggestedScope)}
                        </p>
                        {false &&<Button size={"ultra-small"} preset={'gray'}
                                 className={'w-initial px-3 bg-opacity-20 text-gray-400'} onClick={() => {
                            /*openExamplesPopup('--simple offers branch--')*/
                        }}>
                            <div className={'flex items-center gap-1'}>
                                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"
                                     className="min-w-3 min-h-3 max-w-3 max-h-3">
                                    <path d="M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z"/>
                                    <path fillRule="evenodd"
                                          d="M1.323 11.447C2.811 6.976 7.028 3.75 12.001 3.75c4.97 0 9.185 3.223 10.675 7.69.12.362.12.752 0 1.113-1.487 4.471-5.705 7.697-10.677 7.697-4.97 0-9.186-3.223-10.675-7.69a1.762 1.762 0 0 1 0-1.113ZM17.25 12a5.25 5.25 0 1 1-10.5 0 5.25 5.25 0 0 1 10.5 0Z"
                                          clipRule="evenodd"/>
                                </svg>
                                {__('Examples')}
                            </div>
                        </Button>
                        }                    </div>
                </div>
                <div className="relative flex items-center justify-center" ref={tierButtonRef}>
                    <ReactFlowHandle
                        id="tier"
                        type="source"
                        position={Position.Bottom}
                        className="opacity-0"
                        style={buttonAnchorHandleStyle}
                    />
                    <div className="inline-flex flex-col items-start gap-2 w-fit">
                        <ActionButton
                            label={__('Add Tiers')}
                            icon={tierIcon}
                            onClick={handleAddTier}
                            color={colors.gray}
                            inversedColor={true}
                        />
                        <p className="max-w-29 text-smaller-1 text-gray-500 leading-[14px]" style={{textWrap: 'auto'}}>{__('For bulk & tiered offers')}</p>
                    </div>

                </div>
            </div>
        </div>
    );

    // Horizontal layout (when inside another branch)
    const horizontalSplitContent = (
        <div className="relative flex items-center pl-8" ref={splitContainerRef}>
            {splitPaths && (
                <svg
                    width={splitPaths.width}
                    height={splitPaths.height}
                    viewBox={`0 0 ${splitPaths.width} ${splitPaths.height}`}
                    className={`pointer-events-none absolute inset-0 ${splitLineColor}`}
                >
                    <path
                        d={`M ${splitStartOffset} ${splitPaths.centerY} L ${Math.max(splitStartOffset + splitMinVertical, splitPaths.leftX - splitDiagonalLength)} ${splitPaths.centerY} Q ${Math.max(splitStartOffset + splitMinVertical + 4, splitPaths.leftX - splitDiagonalLength / 2)} ${splitPaths.centerY} ${splitPaths.leftX} ${splitPaths.leftY}`}
                        stroke="currentColor"
                        strokeWidth="2"
                        fill="none"
                        strokeLinecap="round"
                    />
                    <path
                        d={`M ${splitStartOffset} ${splitPaths.centerY} L ${Math.max(splitStartOffset + splitMinVertical, splitPaths.rightX - splitDiagonalLength)} ${splitPaths.centerY} Q ${Math.max(splitStartOffset + splitMinVertical + 4, splitPaths.rightX - splitDiagonalLength / 2)} ${splitPaths.centerY} ${splitPaths.rightX} ${splitPaths.rightY}`}
                        stroke="currentColor"
                        strokeWidth="2"
                        fill="none"
                        strokeLinecap="round"
                    />
                </svg>
            )}

            {/* Two action buttons stacked vertically */}
            <div className="flex flex-col items-start space-y-2">
                <div className="relative flex items-center justify-center" ref={offerButtonRef}>
                    <ReactFlowHandle
                        id="offer"
                        type="source"
                        position={Position.Right}
                        className="opacity-0"
                        style={buttonAnchorHandleStyle}
                    />
                    <ActionButton
                        label={__('Add Offer')}
                        icon={addIcon}
                        onClick={handleAddOffer}
                        color={colors.blue}
                    />
                </div>
                <div className="relative flex items-center justify-center" ref={tierButtonRef}>
                    <ReactFlowHandle
                        id="tier"
                        type="source"
                        position={Position.Right}
                        className="opacity-0"
                        style={buttonAnchorHandleStyle}
                    />
                    <ActionButton
                        label={__('Add Tiers')}
                        icon={tierIcon}
                        onClick={handleAddTier}
                        color={colors.gray}
                        inversedColor={true}
                    />
                </div>
            </div>
        </div>
    );

    return (
        <motion.div
            layout="position"
            transition={{type: 'spring'}}
            className={classNames({
                'flex relative items-center': isInsideBranch,
                'relative overflow-visible': !isInsideBranch
            })}
        >
            {!isInsideBranch ? (
                <>
                    <ReactFlowHandle
                        type="target"
                        position={Position.Top}
                        className="opacity-0 overflow-hidden pointer-events-none !border-0 !bg-transparent !shadow-none"
                        style={{
                            position: 'absolute',
                            top: 0,
                            left: '50%',
                            width: 0,
                            height: 0,
                            padding: 0,
                            margin: 0,
                            minWidth: 0,
                            minHeight: 0,
                            background: 'transparent',
                            border: 'none',
                            boxShadow: 'none',
                            transform: 'translate(-50%, -50%)'
                        }}
                    />
                    {verticalSplitContent}
                </>
            ) : (
                <>
                    {<Handle
                        id="left"
                        type="target"
                        position={Position.Left}
                        color={colors.gray}
                        invisible={true}
                    />}
                    {horizontalSplitContent}
                </>
            )}
        </motion.div>
    );
}
