/**
 * AnalyticsProvider – context + delegated event listener for data-seekora-* attribute-based analytics
 *
 * Installs a delegated click listener on a container. Any descendant with
 * data-seekora-track="click"|"add-to-cart" and data-seekora-product-id="..."
 * automatically fires analytics events without React wiring.
 */
import React, { useRef, useEffect, useCallback, createContext, useContext } from 'react';
import { log } from '@seekora-ai/ui-sdk-core';
const AnalyticsContext = createContext(null);
export const useAnalyticsProvider = () => useContext(AnalyticsContext);
export function AnalyticsProvider({ client, context, children }) {
    const containerRef = useRef(null);
    const sendEvent = useCallback(async (eventName, metadata) => {
        try {
            await client.trackEvent?.({
                event_name: eventName,
                metadata: {
                    timestamp: Date.now(),
                    source: 'analytics_provider_delegation',
                    ...metadata,
                },
            }, context);
            log.verbose(`AnalyticsProvider: ${eventName}`, metadata);
        }
        catch (error) {
            log.warn(`AnalyticsProvider: Failed to track ${eventName}`, { error });
        }
    }, [client, context]);
    useEffect(() => {
        const container = containerRef.current;
        if (!container)
            return;
        const handleClick = (e) => {
            const target = e.target;
            // Walk up from target to find element with data-seekora-track
            const tracked = target.closest('[data-seekora-track]');
            if (!tracked)
                return;
            const trackType = tracked.getAttribute('data-seekora-track');
            const productId = tracked.getAttribute('data-seekora-product-id');
            const position = tracked.getAttribute('data-seekora-position');
            const section = tracked.getAttribute('data-seekora-section');
            const variantSku = tracked.getAttribute('data-seekora-variant-sku');
            const variantOption = tracked.getAttribute('data-seekora-variant-option');
            const variantValue = tracked.getAttribute('data-seekora-variant-value');
            const metadata = {};
            if (productId)
                metadata.product_id = productId;
            if (position)
                metadata.position = parseInt(position, 10);
            if (section)
                metadata.section = section;
            switch (trackType) {
                case 'click':
                    sendEvent('product.click', metadata);
                    if (client?.trackClick && productId) {
                        const pos = position ? parseInt(position, 10) + 1 : 1;
                        Promise.resolve(client.trackClick(productId, pos, context)).catch(() => { });
                    }
                    break;
                case 'add-to-cart':
                    if (variantSku)
                        metadata.variant_sku = variantSku;
                    sendEvent('product.add_to_cart', metadata);
                    break;
                case 'variant-select':
                    if (variantOption)
                        metadata.option_name = variantOption;
                    if (variantValue)
                        metadata.option_value = variantValue;
                    sendEvent('product.variant_select', metadata);
                    break;
                default:
                    // Custom track type — use it as event name
                    if (trackType) {
                        sendEvent(trackType, metadata);
                    }
                    break;
            }
        };
        container.addEventListener('click', handleClick);
        return () => container.removeEventListener('click', handleClick);
    }, [client, context, sendEvent]);
    return (React.createElement(AnalyticsContext.Provider, { value: { client, context } },
        React.createElement("div", { ref: containerRef, style: { display: 'contents' } }, children)));
}
