const { useState, useEffect, useCallback, useRef } = React;

const FlipPriceItem = ({ metal, name, unit, sellPrice, buyPrice, showBuy, isFlipping, delay = 0 }) => {
    const formatPrice = (price) => price ? `$${Math.round(price).toLocaleString()}` : '—';

    const currentLabel = showBuy ? '回收' : '賣出';
    const currentLabelClass = showBuy ? 'buy' : 'sell';
    const currentPrice = showBuy ? buyPrice : sellPrice;
    const currentPriceClass = showBuy ? 'buy' : metal;

    const nextLabel = showBuy ? '賣出' : '回收';
    const nextLabelClass = showBuy ? 'sell' : 'buy';
    const nextPrice = showBuy ? sellPrice : buyPrice;
    const nextPriceClass = showBuy ? metal : 'buy';

    const cardClass = ['flip-card', isFlipping ? 'flipping' : ''].filter(Boolean).join(' ');

    return (
        <div className="flip-price-item" style={{ '--flip-delay': `${delay}ms` }}>
            <div className="flip-metal-name">{name} / {unit}</div>
            <div className={cardClass} style={{ animationDelay: `${delay}ms` }}>
                <div className="flip-half flip-top" style={{ animationDelay: `${delay}ms` }}>
                    <span className={`flip-label ${currentLabelClass}`}>{currentLabel}</span>
                </div>
                <div className="flip-half flip-top-back">
                    <span className={`flip-label ${nextLabelClass}`}>{nextLabel}</span>
                </div>
                <div className="flip-half flip-bottom">
                    <span className={`flip-price ${currentPriceClass}`}>{formatPrice(currentPrice)}</span>
                </div>
                <div className="flip-half flip-bottom-back" style={{ animationDelay: `${delay + 300}ms` }}>
                    <span className={`flip-price ${nextPriceClass}`}>{formatPrice(nextPrice)}</span>
                </div>
            </div>
        </div>
    );
};

const PriceBanner = ({ prices }) => {
    const { user, handleLogin, authReady } = useApp();
    const [showBuyPrice, setShowBuyPrice] = useState(false);
    const [isFlipping, setIsFlipping] = useState(false);
    const flipTimeoutRef = useRef(null);
    const autoFlipRef = useRef(null);

    const handleFlip = useCallback(() => {
        if (isFlipping) return;

        setIsFlipping(true);

        flipTimeoutRef.current = setTimeout(() => {
            setShowBuyPrice(prev => !prev);
            setIsFlipping(false);
        }, 700);

        if (autoFlipRef.current) {
            clearInterval(autoFlipRef.current);
            autoFlipRef.current = setInterval(() => {
                handleFlip();
            }, 5000);
        }
    }, [isFlipping]);

    useEffect(() => {
        if (!user || !prices?.has_prices) return;

        autoFlipRef.current = setInterval(() => {
            handleFlip();
        }, 5000);

        return () => {
            if (autoFlipRef.current) clearInterval(autoFlipRef.current);
        };
    }, [user, prices?.has_prices, handleFlip]);

    useEffect(() => {
        return () => {
            if (flipTimeoutRef.current) clearTimeout(flipTimeoutRef.current);
            if (autoFlipRef.current) clearInterval(autoFlipRef.current);
        };
    }, []);

    if (!prices?.has_prices) return null;

    const p = prices.prices || {};

    if (!user) {
        return (
            <div className="price-banner price-banner-locked" onClick={authReady ? handleLogin : undefined}>
                <div className="price-banner-lock-msg">
                    <svg width="14" height="14" viewBox="0 0 16 16" fill="none">
                        <rect x="3" y="7" width="10" height="7" rx="1.5" stroke="currentColor" strokeWidth="1.5" fill="none"/>
                        <path d="M5 7V5a3 3 0 0 1 6 0v2" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" fill="none"/>
                    </svg>
                    <span>登入查看即時報價</span>
                </div>
            </div>
        );
    }

    return (
        <div className="price-banner price-banner-flip" onClick={handleFlip}>
            <FlipPriceItem
                metal="gold"
                name="黃金"
                unit={p.Au?.display_unit || '錢'}
                sellPrice={p.Au?.sell_price}
                buyPrice={p.Au?.buy_price}
                showBuy={showBuyPrice}
                isFlipping={isFlipping}
                delay={0}
            />
            <FlipPriceItem
                metal="silver"
                name="白銀"
                unit={p.Ag?.display_unit || '公斤'}
                sellPrice={p.Ag?.sell_price}
                buyPrice={p.Ag?.buy_price}
                showBuy={showBuyPrice}
                isFlipping={isFlipping}
                delay={100}
            />
            <FlipPriceItem
                metal="platinum"
                name="白金"
                unit={p.Pt?.display_unit || '錢'}
                sellPrice={p.Pt?.sell_price}
                buyPrice={p.Pt?.buy_price}
                showBuy={showBuyPrice}
                isFlipping={isFlipping}
                delay={200}
            />
        </div>
    );
};
