/**
 * Recommendation Components
 *
 * Components for displaying product recommendations:
 * - RelatedProducts: Show related items based on a product
 * - TrendingItems: Display trending/popular products
 * - FrequentlyBoughtTogether: Bundle recommendations
 * - RecentlyViewed: User's recently viewed items
 */
import React, { useEffect, useState, useMemo } from 'react';
import { useSearchContext } from './SearchProvider';
import { clsx } from 'clsx';
export const RelatedProducts = ({ productId, items: itemsProp, loading: loadingProp = false, title = 'Related Products', maxItems = 6, renderItem, onItemClick, className, style, theme: customTheme, layout = 'horizontal', currencySymbol = '$', }) => {
    const { theme } = useSearchContext();
    const recommendationTheme = customTheme || {};
    // If items are provided, use them directly
    const items = itemsProp?.slice(0, maxItems) || [];
    const loading = loadingProp;
    if (loading && items.length === 0)
        return null;
    if (items.length === 0) {
        return null;
    }
    return (React.createElement(RecommendationSection, { title: title, items: items, renderItem: renderItem, onItemClick: onItemClick, className: className, style: style, theme: customTheme, layout: layout, currencySymbol: currencySymbol }));
};
export const TrendingItems = ({ items: itemsProp, loading: loadingProp = false, title = 'Trending Now', maxItems = 8, renderItem, onItemClick, className, style, theme: customTheme, layout = 'horizontal', currencySymbol = '$', }) => {
    const { theme } = useSearchContext();
    const recommendationTheme = customTheme || {};
    const items = itemsProp?.slice(0, maxItems) || [];
    const loading = loadingProp;
    if (loading && items.length === 0)
        return null;
    if (items.length === 0) {
        return null;
    }
    return (React.createElement(RecommendationSection, { title: title, items: items, renderItem: renderItem, onItemClick: onItemClick, className: className, style: style, theme: customTheme, layout: layout, currencySymbol: currencySymbol }));
};
export const FrequentlyBoughtTogether = ({ productId, items: itemsProp, loading: loadingProp = false, title = 'Frequently Bought Together', maxItems = 4, renderItem, onItemClick, className, style, theme: customTheme, layout = 'horizontal', currencySymbol = '$', showAddAllButton = true, onAddAll, }) => {
    const { theme } = useSearchContext();
    const recommendationTheme = customTheme || {};
    const items = itemsProp?.slice(0, maxItems) || [];
    const loading = loadingProp;
    // Calculate total price
    const totalPrice = useMemo(() => {
        return items.reduce((sum, item) => {
            const itemPrice = item.price;
            const price = typeof itemPrice === 'number' ? itemPrice : parseFloat(String(itemPrice)) || 0;
            return sum + price;
        }, 0);
    }, [items]);
    if (loading && items.length === 0)
        return null;
    if (items.length === 0) {
        return null;
    }
    return (React.createElement("div", { className: clsx(recommendationTheme.root, className), style: style },
        title && (React.createElement("h3", { className: recommendationTheme.title, style: {
                margin: `0 0 ${theme.spacing.medium} 0`,
                fontSize: theme.typography.fontSize.large,
                fontWeight: theme.typography.fontWeight?.semibold || 600,
                color: theme.colors.text,
            } }, title)),
        React.createElement("div", { style: {
                display: 'flex',
                alignItems: 'center',
                gap: theme.spacing.medium,
                flexWrap: 'wrap',
            } },
            items.map((item, index) => (React.createElement(React.Fragment, { key: item.id || index },
                index > 0 && (React.createElement("span", { style: { fontSize: '1.5rem', color: theme.colors.textSecondary } }, "+")),
                React.createElement("div", { onClick: () => onItemClick?.(item, index), style: {
                        cursor: onItemClick ? 'pointer' : 'default',
                        textAlign: 'center',
                    } }, renderItem ? (renderItem(item, index)) : (React.createElement(React.Fragment, null,
                    React.createElement("img", { src: item.image || item.imageUrl || '', alt: item.title || item.name || '', style: {
                            width: '80px',
                            height: '80px',
                            objectFit: 'cover',
                            borderRadius: typeof theme.borderRadius === 'string'
                                ? theme.borderRadius
                                : theme.borderRadius.small,
                            border: `1px solid ${theme.colors.border}`,
                        } }),
                    React.createElement("div", { style: {
                            marginTop: theme.spacing.small,
                            fontSize: theme.typography.fontSize.small,
                            color: theme.colors.text,
                        } },
                        currencySymbol,
                        typeof item.price === 'number' ? item.price.toFixed(2) : item.price))))))),
            showAddAllButton && items.length > 0 && (React.createElement("div", { style: {
                    marginLeft: 'auto',
                    textAlign: 'center',
                } },
                React.createElement("div", { style: {
                        fontSize: theme.typography.fontSize.large,
                        fontWeight: theme.typography.fontWeight?.bold || 700,
                        color: theme.colors.text,
                        marginBottom: theme.spacing.small,
                    } },
                    "Total: ",
                    currencySymbol,
                    totalPrice.toFixed(2)),
                React.createElement("button", { type: "button", onClick: () => onAddAll?.(items), style: {
                        padding: `${theme.spacing.small} ${theme.spacing.medium}`,
                        fontSize: theme.typography.fontSize.medium,
                        fontWeight: theme.typography.fontWeight?.medium || 500,
                        color: '#ffffff',
                        backgroundColor: theme.colors.primary,
                        border: 'none',
                        borderRadius: typeof theme.borderRadius === 'string'
                            ? theme.borderRadius
                            : theme.borderRadius.medium,
                        cursor: 'pointer',
                    } }, "Add all to cart"))))));
};
export const RecentlyViewed = ({ storageKey = 'seekora_recently_viewed', items: itemsProp, title = 'Recently Viewed', maxItems = 6, renderItem, onItemClick, className, style, theme: customTheme, layout = 'horizontal', currencySymbol = '$', }) => {
    const [storedItems, setStoredItems] = useState([]);
    useEffect(() => {
        if (itemsProp)
            return;
        try {
            const stored = localStorage.getItem(storageKey);
            if (stored) {
                setStoredItems(JSON.parse(stored));
            }
        }
        catch (e) {
            // Ignore localStorage errors
        }
    }, [storageKey, itemsProp]);
    const items = (itemsProp || storedItems).slice(0, maxItems);
    if (items.length === 0) {
        return null;
    }
    return (React.createElement(RecommendationSection, { title: title, items: items, renderItem: renderItem, onItemClick: onItemClick, className: className, style: style, theme: customTheme, layout: layout, currencySymbol: currencySymbol }));
};
/**
 * Add item to recently viewed (utility function)
 */
export function addToRecentlyViewed(item, storageKey = 'seekora_recently_viewed', maxItems = 20) {
    if (typeof localStorage === 'undefined')
        return;
    try {
        const stored = localStorage.getItem(storageKey);
        let items = stored ? JSON.parse(stored) : [];
        // Remove if already exists
        items = items.filter(i => i.id !== item.id);
        // Add to beginning
        items.unshift(item);
        // Limit
        items = items.slice(0, maxItems);
        localStorage.setItem(storageKey, JSON.stringify(items));
    }
    catch (e) {
        // Ignore localStorage errors
    }
}
const RecommendationSection = ({ title, items, renderItem, onItemClick, className, style, theme: customTheme, layout = 'horizontal', currencySymbol = '$', }) => {
    const { theme } = useSearchContext();
    const recommendationTheme = customTheme || {};
    const getListStyle = () => {
        switch (layout) {
            case 'horizontal':
                return {
                    display: 'flex',
                    gap: theme.spacing.medium,
                    overflowX: 'auto',
                    scrollSnapType: 'x mandatory',
                    paddingBottom: theme.spacing.small,
                };
            case 'grid':
                return {
                    display: 'grid',
                    gridTemplateColumns: 'repeat(auto-fill, minmax(150px, 1fr))',
                    gap: theme.spacing.medium,
                };
            case 'list':
                return {
                    display: 'flex',
                    flexDirection: 'column',
                    gap: theme.spacing.small,
                };
            default:
                return {};
        }
    };
    const getItemStyle = () => {
        switch (layout) {
            case 'horizontal':
                return {
                    flexShrink: 0,
                    width: '150px',
                    scrollSnapAlign: 'start',
                };
            case 'grid':
                return {};
            case 'list':
                return {
                    display: 'flex',
                    gap: theme.spacing.medium,
                    padding: theme.spacing.small,
                    borderBottom: `1px solid ${theme.colors.border}`,
                };
            default:
                return {};
        }
    };
    return (React.createElement("div", { className: clsx(recommendationTheme.root, className), style: style },
        title && (React.createElement("h3", { className: recommendationTheme.title, style: {
                margin: `0 0 ${theme.spacing.medium} 0`,
                fontSize: theme.typography.fontSize.large,
                fontWeight: theme.typography.fontWeight?.semibold || 600,
                color: theme.colors.text,
            } }, title)),
        React.createElement("div", { className: recommendationTheme.list, style: getListStyle() }, items.map((item, index) => (React.createElement("div", { key: item.id || index, className: recommendationTheme.item, onClick: () => onItemClick?.(item, index), style: {
                ...getItemStyle(),
                cursor: onItemClick ? 'pointer' : 'default',
            } }, renderItem ? (renderItem(item, index)) : (React.createElement(DefaultRecommendationItem, { item: item, theme: recommendationTheme, currencySymbol: currencySymbol, layout: layout }))))))));
};
const DefaultRecommendationItem = ({ item, theme: recommendationTheme, currencySymbol, layout, }) => {
    const { theme } = useSearchContext();
    const image = item.image || item.imageUrl || '';
    const title = item.title || item.name || '';
    const price = item.price;
    const imageSize = layout === 'list' ? '60px' : '100%';
    return (React.createElement(React.Fragment, null,
        image && (React.createElement("img", { src: image, alt: title, className: recommendationTheme.image, style: {
                width: imageSize,
                height: layout === 'list' ? '60px' : '120px',
                objectFit: 'cover',
                borderRadius: typeof theme.borderRadius === 'string'
                    ? theme.borderRadius
                    : theme.borderRadius.small,
            } })),
        React.createElement("div", { className: recommendationTheme.content, style: { flex: layout === 'list' ? 1 : undefined } },
            React.createElement("div", { className: recommendationTheme.name, style: {
                    marginTop: layout === 'list' ? 0 : theme.spacing.small,
                    fontSize: theme.typography.fontSize.small,
                    fontWeight: theme.typography.fontWeight?.medium || 500,
                    color: theme.colors.text,
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    display: '-webkit-box',
                    WebkitLineClamp: 2,
                    WebkitBoxOrient: 'vertical',
                } }, title),
            price !== undefined && (React.createElement("div", { className: recommendationTheme.price, style: {
                    marginTop: theme.spacing.small,
                    fontSize: theme.typography.fontSize.small,
                    fontWeight: theme.typography.fontWeight?.bold || 700,
                    color: theme.colors.primary,
                } },
                currencySymbol,
                typeof price === 'number' ? price.toFixed(2) : price)))));
};
