// Svelte action: show the full text in a native `title` tooltip only when
// the element is actually truncated (ellipsis or line-clamp), and keep it in
// sync as the element resizes or the text changes.
//
// Native `title` is deliberate: it's keyboard/touch reachable and zero-dep,
// unlike a hover-only custom popover. Applied to clipped titles across list
// surfaces (MangaCard, BookmarkList, HistoryList).

/** True when the element's content is clipped horizontally (ellipsis) or
 *  vertically (line-clamp). A 1px slack absorbs sub-pixel rounding. */
export function isOverflowing(node: HTMLElement): boolean {
    return (
        node.scrollWidth - node.clientWidth > 1 ||
        node.scrollHeight - node.clientHeight > 1
    );
}

export function overflowTooltip(node: HTMLElement, text: string) {
    let current = text;

    function sync() {
        if (isOverflowing(node)) node.setAttribute('title', current);
        else node.removeAttribute('title');
    }

    // Re-check on size changes (viewport resize, font load, layout shifts).
    // Guarded for environments without ResizeObserver (SSR / jsdom).
    let ro: ResizeObserver | undefined;
    if (typeof ResizeObserver !== 'undefined') {
        ro = new ResizeObserver(() => sync());
        ro.observe(node);
    }

    sync();

    return {
        update(next: string) {
            current = next;
            sync();
        },
        destroy() {
            ro?.disconnect();
        }
    };
}
