// src/components/store/ProductCard.jsx
import { useNavigate } from 'react-router-dom';
import ReactMarkdown from 'react-markdown';
import { ShoppingCart, CheckCircle2 } from 'lucide-react';
import { parsePeriod, getCategoryBadge } from './StoreHelpers';

export default function ProductCard({ product, selectedPeriod, categoryName }) {
    const navigate = useNavigate();
    
    const getPricingData = () => {
        if (product.pricing?.type !== 'recurrent' || !product.pricing?.recurrent) {
            const oncePrice = product.pricing?.once?.price ? parseFloat(product.pricing.once.price).toFixed(2) : '0.00';
            return { isAvailable: true, displayPrice: oncePrice, suffix: '(Une fois)', originalPrice: null, savingsPercent: 0, isOnce: true };
        }

        const recurrentPrices = product.pricing.recurrent;
        const availablePeriods = Object.keys(recurrentPrices).filter(
            period => recurrentPrices[period].enabled == 1 || recurrentPrices[period].enabled === true
        );
        
        if (!recurrentPrices[selectedPeriod] || !availablePeriods.includes(selectedPeriod)) return { isAvailable: false };

        const currentPrice = parseFloat(recurrentPrices[selectedPeriod].price);
        const currentPeriodInfo = parsePeriod(selectedPeriod);
        const currentYearlyCost = currentPrice * currentPeriodInfo.factorToYear;
        const currentMonthlyEquivalent = currentYearlyCost / 12;

        let savingsPercent = 0;
        let originalPrice = null; 
        
        const sortedAvailablePeriods = [...availablePeriods].sort((a, b) => parsePeriod(a).weight - parsePeriod(b).weight);
        const basePeriodCode = sortedAvailablePeriods[0];
        
        if (basePeriodCode !== selectedPeriod) {
            const basePrice = parseFloat(recurrentPrices[basePeriodCode].price);
            const basePeriodInfo = parsePeriod(basePeriodCode);
            const baseYearlyCost = basePrice * basePeriodInfo.factorToYear;
            const baseMonthlyEquivalent = baseYearlyCost / 12;

            if (baseYearlyCost > currentYearlyCost) {
                savingsPercent = Math.round((1 - (currentYearlyCost / baseYearlyCost)) * 100);
                originalPrice = baseMonthlyEquivalent.toFixed(2);
            }
        }

        return {
            isAvailable: true, displayPrice: currentMonthlyEquivalent.toFixed(2), suffix: '/ mois',
            originalPrice, savingsPercent, billingPrice: currentPrice.toFixed(2), 
            billingPhrase: currentPeriodInfo.billingPhrase, isOnce: false
        };
    };

    const priceData = getPricingData();

    return (
        <div className={`bg-gray-900 border border-gray-800 rounded-2xl overflow-hidden hover:border-cyan-400/50 transition-all duration-300 flex flex-col relative group ${!priceData.isAvailable ? 'opacity-50 grayscale' : ''}`}>
            <div className="absolute top-4 left-4 z-20">
                <span className="bg-black/60 backdrop-blur-sm text-gray-300 text-xs font-black px-3 py-1 rounded border border-gray-800 tracking-widest shadow-sm">
                    {getCategoryBadge(categoryName)}
                </span>
            </div>

            {priceData.savingsPercent > 0 && priceData.isAvailable && (
                <div className="absolute top-4 right-4 z-20 bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 text-xs font-bold px-3 py-1 rounded-full animate-pulse shadow-[0_0_15px_rgba(16,185,129,0.2)]">
                    ÉCONOMIE {priceData.savingsPercent}%
                </div>
            )}

            <div className="p-8 pt-14 border-b border-gray-800 relative bg-linear-to-b from-gray-800/30 to-transparent min-h-47.5 flex flex-col">
                <h3 className="text-2xl font-bold text-white mb-4 relative z-10">{product.title}</h3>
                
                {priceData.isAvailable ? (
                    <div className="grow flex flex-col justify-end">
                        <div className="flex items-baseline space-x-2">
                            <span className="text-4xl font-black text-cyan-400">{priceData.displayPrice} €</span>
                            <span className="text-gray-500">{priceData.suffix}</span>
                        </div>
                        <div className="mt-3 min-h-11 flex flex-col justify-end">
                            {!priceData.isOnce && (
                                <>
                                    {priceData.originalPrice ? (
                                        <div className="text-sm text-gray-500">Au lieu de <span className="line-through">{priceData.originalPrice} €</span> / mois</div>
                                    ) : (
                                        <div className="text-sm text-gray-600 italic">Tarif de base équivalent</div>
                                    )}
                                    <div className="text-xs text-cyan-500 mt-1 font-semibold uppercase tracking-wider bg-cyan-500/10 inline-block px-2 py-1 rounded w-max">
                                        Facturé {priceData.billingPrice} € {priceData.billingPhrase}
                                    </div>
                                </>
                            )}
                            {priceData.isOnce && <div className="text-sm text-gray-500">Paiement unique</div>}
                        </div>
                    </div>
                ) : (
                    <div className="text-red-400 font-medium mt-auto">Non disponible pour cette durée.</div>
                )}
            </div>
            
            <div className="p-8 grow flex flex-col justify-between">
                <div className="text-gray-400 text-sm mb-8 space-y-3 prose prose-invert max-w-none">
                    <ReactMarkdown components={{ ul: ({node, ...props}) => <ul className="space-y-2" {...props} />, li: ({node, ...props}) => <li className="flex items-start space-x-2"><CheckCircle2 className="w-4 h-4 text-cyan-400 mt-0.5 shrink-0"/> <span>{props.children}</span></li>, p: ({node, ...props}) => <p className="mb-2 text-gray-300" {...props} />, strong: ({node, ...props}) => <strong className="text-white font-semibold" {...props} /> }}>
                        {product.description || "Aucune description technique."}
                    </ReactMarkdown>
                </div>

                <button disabled={!priceData.isAvailable} onClick={() => navigate(`/checkout/${product.id}?period=${selectedPeriod}`)} className={`w-full py-3 rounded-lg font-bold tracking-widest transition-all flex justify-center items-center space-x-2 ${priceData.isAvailable ? "bg-cyan-400/10 hover:bg-cyan-400 text-cyan-400 hover:text-gray-900 border border-cyan-400 group-hover:shadow-[0_0_20px_rgba(34,211,238,0.2)]" : "bg-gray-800 text-gray-600 border border-gray-800 cursor-not-allowed"}`}>
                    <ShoppingCart className="w-5 h-5" /><span>COMMANDER</span>
                </button>
            </div>
        </div>
    );
}