// Scroll position utilities for maintaining scroll state across navigation

window.getScrollPosition = function(elementId) {
    const element = document.getElementById(elementId) || document.querySelector(`[data-ref="${elementId}"]`);
    if (element) {
        return element.scrollTop;
    }
    const scroller = document.scrollingElement || document.documentElement || document.body;
    return scroller ? scroller.scrollTop || 0 : 0;
};

window.setScrollPosition = function(elementId, position) {
    const element = document.getElementById(elementId) || document.querySelector(`[data-ref="${elementId}"]`);
    if (element) {
        element.scrollTop = position;
    } else {
        const scroller = document.scrollingElement || document.documentElement || document.body;
        if (scroller) {
            scroller.scrollTop = position;
        }
        window.scrollTo(0, position);
    }
};

window.resetElementAndAncestorScrollPositions = function(elementId) {
    const element = document.getElementById(elementId) || document.querySelector(`[data-ref="${elementId}"]`);
    if (!element) {
        return;
    }

    const resetScroll = (target) => {
        if (!target || typeof target.scrollTop !== 'number') {
            return;
        }

        target.scrollTop = 0;
    };

    const collectTargets = () => {
        const targets = [element];
        let current = element.parentElement;

        while (current) {
            const styles = window.getComputedStyle(current);
            const overflowY = styles.overflowY;
            const isScrollable = (overflowY === 'auto' || overflowY === 'scroll') && current.scrollHeight > current.clientHeight;
            if (isScrollable || current.classList.contains('e-dlg-content')) {
                targets.push(current);
            }

            current = current.parentElement;
        }

        const rootScroller = document.scrollingElement || document.documentElement || document.body;
        if (rootScroller) {
            targets.push(rootScroller);
        }

        return targets;
    };

    const applyReset = () => {
        const targets = collectTargets();
        targets.forEach(resetScroll);
        window.scrollTo(0, 0);
    };

    applyReset();
    requestAnimationFrame(applyReset);
    setTimeout(applyReset, 60);
};

// Optimized scrolling for better performance
window.enableSmoothScrolling = function(elementId) {
    const element = document.getElementById(elementId) || document.querySelector(`[data-ref="${elementId}"]`);
    if (element) {
        element.style.scrollBehavior = 'smooth';
        // Use CSS containment for better performance
        element.style.contain = 'layout style paint';
        // Enable hardware acceleration
        element.style.transform = 'translateZ(0)';
        element.style.willChange = 'scroll-position';
    }
};

// Disable smooth scrolling for instant positioning
window.disableSmoothScrolling = function(elementId) {
    const element = document.getElementById(elementId) || document.querySelector(`[data-ref="${elementId}"]`);
    if (element) {
        element.style.scrollBehavior = 'auto';
    }
};

// Optimize scroll performance with passive listeners and debouncing
window.optimizeScrollPerformance = function(elementId) {
    const element = document.getElementById(elementId) || document.querySelector(`[data-ref="${elementId}"]`);
    if (element) {
        // Enable CSS containment for better performance
        element.style.contain = 'layout style paint';
        
        // Use transform3d to enable hardware acceleration
        element.style.transform = 'translate3d(0,0,0)';
        
        // Optimize rendering
        element.style.backfaceVisibility = 'hidden';
        element.style.perspective = '1000px';
        
        // Add passive scroll listeners for better performance
        let ticking = false;
        
        const optimizeFrame = () => {
            // Force composite layer creation for smoother scrolling
            element.style.willChange = 'scroll-position';
            ticking = false;
        };
        
        element.addEventListener('scroll', () => {
            if (!ticking) {
                requestAnimationFrame(optimizeFrame);
                ticking = true;
            }
        }, { passive: true });
    }
};

// Scroll to a specific element by ID with smooth scrolling
window.scrollToElement = function(elementId) {
    const element = document.getElementById(elementId);
    if (element) {
        element.scrollIntoView({ 
            behavior: 'smooth', 
            block: 'start',
            inline: 'nearest'
        });
    }
};

window.scrollToElementWithStickyOffset = function(elementId, stickySelector, extraOffset = 0) {
    const element = document.getElementById(elementId);
    if (!element) {
        return;
    }

    const getScrollableAncestor = (node) => {
        let current = node?.parentElement;
        while (current) {
            const styles = window.getComputedStyle(current);
            const overflowY = styles.overflowY;
            const isScrollable = (overflowY === 'auto' || overflowY === 'scroll') && current.scrollHeight > current.clientHeight;
            if (isScrollable) {
                return current;
            }
            current = current.parentElement;
        }

        return document.scrollingElement || document.documentElement;
    };

    let stickyHeight = 0;
    if (stickySelector) {
        const stickyElement = document.querySelector(stickySelector);
        if (stickyElement) {
            const stickyRect = stickyElement.getBoundingClientRect();
            const stickyStyles = window.getComputedStyle(stickyElement);
            const isVisible = stickyStyles.display !== 'none' && stickyStyles.visibility !== 'hidden' && stickyRect.height > 0;

            if (isVisible) {
                stickyHeight = stickyRect.height;
            }
        }
    }

    const scrollContainer = getScrollableAncestor(element);
    const elementRect = element.getBoundingClientRect();
    const isRootScroller = scrollContainer === document.body
        || scrollContainer === document.documentElement
        || scrollContainer === document.scrollingElement;

    if (isRootScroller) {
        const elementPosition = elementRect.top + window.pageYOffset;
        const targetPosition = Math.max(elementPosition - stickyHeight - extraOffset, 0);

        window.scrollTo({
            top: targetPosition,
            behavior: 'smooth'
        });
        return;
    }

    const containerRect = scrollContainer.getBoundingClientRect();
    const currentScrollTop = scrollContainer.scrollTop;
    const targetPosition = Math.max(
        currentScrollTop + (elementRect.top - containerRect.top) - stickyHeight - extraOffset,
        0
    );

    scrollContainer.scrollTo({
        top: targetPosition,
        behavior: 'smooth'
    });
};

window.__astroManagerShareState = window.__astroManagerShareState || { inProgress: false };

// Share functionality with fallback support
window.shareContent = async function(shareData) {
    const shareState = window.__astroManagerShareState || (window.__astroManagerShareState = { inProgress: false });

    if (shareState.inProgress) {
        return { success: false, busy: true, cancelled: true };
    }

    shareState.inProgress = true;

    try {
        if (navigator.share) {
            try {
                const canShare = !navigator.canShare || navigator.canShare(shareData);
                if (canShare) {
                    await navigator.share(shareData);
                    return { success: true, method: 'native' };
                }
            } catch (error) {
                if (error?.name === 'AbortError') {
                    return { success: false, cancelled: true };
                }
            }
        }

        if (navigator.clipboard && navigator.clipboard.writeText) {
            try {
                await navigator.clipboard.writeText(shareData.url);
                return { success: true, method: 'clipboard' };
            } catch {
                // Continue to legacy/manual fallbacks when clipboard permissions are denied.
            }
        }

        const textArea = document.createElement('textarea');
        textArea.value = shareData.url;
        textArea.style.position = 'fixed';
        textArea.style.left = '-999999px';
        textArea.style.top = '-999999px';
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();

        try {
            const successful = document.execCommand('copy');
            document.body.removeChild(textArea);
            if (successful) {
                return { success: true, method: 'execCommand' };
            }
        } catch (err) {
            document.body.removeChild(textArea);
        }

        if (typeof window.prompt === 'function') {
            window.prompt('Copy this link:', shareData.url);
            return { success: true, method: 'prompt' };
        }

        return { success: false, error: 'Unable to share or copy link.' };
    } catch (error) {
        console.error('Share failed:', error);
        return { success: false, error: error?.message || 'Unable to share or copy link.' };
    } finally {
        shareState.inProgress = false;
    }
};

window.copyTextToClipboard = window.copyTextToClipboard || async function(text) {
    try {
        if (navigator.clipboard && navigator.clipboard.writeText) {
            try {
                await navigator.clipboard.writeText(text);
                return { success: true, method: 'clipboard' };
            } catch {
                // Continue to legacy/manual fallbacks when clipboard permissions are denied.
            }
        }

        const textArea = document.createElement('textarea');
        textArea.value = text;
        textArea.style.position = 'fixed';
        textArea.style.left = '-999999px';
        textArea.style.top = '-999999px';
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();

        try {
            const successful = document.execCommand('copy');
            document.body.removeChild(textArea);
            if (successful) {
                return { success: true, method: 'execCommand' };
            }
        } catch (err) {
            document.body.removeChild(textArea);
        }

        if (typeof window.prompt === 'function') {
            window.prompt('Copy this text:', text);
            return { success: true, method: 'prompt' };
        }

        return { success: false, error: 'Unable to copy link.' };
    } catch (error) {
        return { success: false, error: error?.message || 'Unable to copy link.' };
    }
};

window.astroManagerAttemptOpen = function(customSchemeUrl, fallbackUrl, timeoutMs = 4500) {
    if (!customSchemeUrl || !fallbackUrl) {
        return;
    }

    const startedAt = Date.now();
    let openedNativeApp = false;

    const cleanup = () => {
        document.removeEventListener('visibilitychange', handleVisibilityChange);
        window.removeEventListener('pagehide', handlePageHide);
        window.removeEventListener('blur', handleBlur);
    };

    const handleVisibilityChange = () => {
        if (document.visibilityState === 'hidden') {
            openedNativeApp = true;
        }
    };

    const handlePageHide = () => {
        openedNativeApp = true;
    };

    const handleBlur = () => {
        if (Date.now() - startedAt < timeoutMs + 400) {
            openedNativeApp = openedNativeApp || document.visibilityState === 'hidden';
        }
    };

    document.addEventListener('visibilitychange', handleVisibilityChange);
    window.addEventListener('pagehide', handlePageHide);
    window.addEventListener('blur', handleBlur);

    window.setTimeout(() => {
        cleanup();
        if (!openedNativeApp && document.visibilityState === 'visible') {
            window.location.replace(fallbackUrl);
        }
    }, timeoutMs);

    window.location.href = customSchemeUrl;
};
