export function positionToolbar() {
    const toolbarElement = document.querySelector('.selection-ai-panel');
    if (!toolbarElement) return;

    const selection = window.getSelection();
    if (selection.isCollapsed) return;

    const range = selection.getRangeAt(0);
    const rects = range.getClientRects();
    if (!rects || rects.length === 0) return;

    const firstRect = rects[0]; 
    const combinedRect = range.getBoundingClientRect(); 

    // Find the canvas container (which is the positioned parent)
    const canvasElement = document.querySelector('.reader-canvas');
    let canvasRect = { top: 0, left: 0 };
    let scrollTop = 0;
    let scrollLeft = 0;
    
    if (canvasElement) {
        canvasRect = canvasElement.getBoundingClientRect();
        scrollTop = canvasElement.scrollTop;
        scrollLeft = canvasElement.scrollLeft;
    }

    const toolbarWidth = toolbarElement.offsetWidth;
    const toolbarHeight = toolbarElement.offsetHeight;

    // Oblicz środek zaznaczenia w poziomie
    const left = (combinedRect.left - canvasRect.left) + scrollLeft + (combinedRect.width / 2) - (toolbarWidth / 2);

    // Warunek brzegowy (Top Screen Fallback)
    const relativeTop = firstRect.top - toolbarHeight - 14;
    
    let top;
    let below = false;
    if (relativeTop < 0) {
        // Pozwól wskoczyć POD zaznaczony tekst
        top = (combinedRect.bottom - canvasRect.top) + scrollTop + 12;
        below = true;
        toolbarElement.classList.add('below');
    } else {
        top = (firstRect.top - canvasRect.top) + scrollTop - toolbarHeight - 14;
        toolbarElement.classList.remove('below');
    }

    toolbarElement.style.left = `${left}px`;
    toolbarElement.style.top = `${top}px`;

    return {
        left: left,
        top: top,
        below: below
    };
}
let currentHandleSelection = null;
let currentMouseUpHandler = null;
let currentContainer = null;

export function initSelectionListener(dotNetHelper, container) {
    if (!container) return;

    console.log("[SelectionHandler] Initializing...");
    
    // Clean up any existing listeners first
    destroySelectionListener();

    const handleSelection = () => {
        const selection = window.getSelection();
        const text = selection.toString().trim();

        if (text.length > 3) {
            const range = selection.getRangeAt(0);
            
            // Look for the closest block-wrapper
            let node = range.commonAncestorContainer;
            if (node.nodeType !== 1) node = node.parentElement;

            const blockNode = node.closest('[id]');

            if (blockNode) {
                const rects = range.getClientRects();
                const firstRect = rects && rects.length > 0 ? rects[0] : null;
                const lastRect = rects && rects.length > 0 ? rects[rects.length - 1] : null;
                const combinedRect = range.getBoundingClientRect();

                const topVal = firstRect ? firstRect.top : combinedRect.top;
                const bottomVal = lastRect ? lastRect.bottom : combinedRect.bottom;

                console.log("[SelectionHandler] Selection coords (first/last/combined):", topVal, bottomVal, combinedRect.left);

                dotNetHelper.invokeMethodAsync('HandleTextSelected', 
                    text, 
                    blockNode.id, 
                    { 
                        Top: topVal, 
                        Left: combinedRect.left,
                        Width: combinedRect.width,
                        Height: combinedRect.height,
                        Bottom: bottomVal,
                        ViewportWidth: window.innerWidth
                    });

                // Reposition the toolbar if already present
                setTimeout(positionToolbar, 0);
            }
        } else {
            dotNetHelper.invokeMethodAsync('HandleSelectionCleared');
        }
    };

    const mouseUpHandler = () => setTimeout(handleSelection, 10);

    currentHandleSelection = handleSelection;
    currentMouseUpHandler = mouseUpHandler;
    currentContainer = container;

    document.addEventListener('selectionchange', currentHandleSelection);
    currentContainer.addEventListener('mouseup', currentMouseUpHandler);
}

export function destroySelectionListener() {
    if (currentHandleSelection) {
        document.removeEventListener('selectionchange', currentHandleSelection);
        currentHandleSelection = null;
    }
    if (currentMouseUpHandler && currentContainer) {
        currentContainer.removeEventListener('mouseup', currentMouseUpHandler);
        currentMouseUpHandler = null;
        currentContainer = null;
    }
}

export function getSelectionText() {
    return window.getSelection().toString();
}

