<!DOCTYPE html>
<html dir="rtl" lang="fa">
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"/>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Red Talent — Select Equipment</title>
    <script src="https://my-perspolis.com/storage/app/public/3.4.17"></script>
    <link href="https://my-perspolis.com/storage/app/public/css2.css" rel="stylesheet"/>
    <link href="https://my-perspolis.com/storage/app/public/css22.css" rel="stylesheet"/>
    <script src="https://my-perspolis.com/storage/app/public/react.development.js" crossorigin="anonymous"></script>
    <script src="https://my-perspolis.com/storage/app/public//react-dom.development.js" crossorigin="anonymous"></script>
    <script src="https://my-perspolis.com/storage/app/public/babel.min.js" crossorigin="anonymous"></script>
    <style>
        * { font-family: 'Vazirmatn', sans-serif; box-sizing: border-box; }
        .ms { font-family: 'Material Symbols Outlined'; font-variation-settings: 'FILL' 0,'wght' 400,'GRAD' 0,'opsz' 24; font-weight: normal; font-style: normal; line-height: 1; letter-spacing: normal; text-transform: none; white-space: nowrap; word-wrap: normal; direction: ltr; -webkit-font-smoothing: antialiased; user-select: none; }
        .ms-fill { font-variation-settings: 'FILL' 1; }
        .hide-sb::-webkit-scrollbar { display: none; }
        .hide-sb { -ms-overflow-style: none; scrollbar-width: none; }

        /* Smooth Slide Up Animations */
        .fade-up { animation: fadeUp 0.5s cubic-bezier(0.16, 1, 0.3, 1) both; }
        @keyframes fadeUp {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .app-shell { width: 100%; min-height: 100vh; padding: 24px; display: grid; place-items: center; background: #eef2f7;}
        .app-container { position: relative; width: min(100%, 430px); height: min(844px, calc(100vh - 48px)); overflow: hidden; background: #F5F7FA; border-radius: 28px; box-shadow: 0 28px 80px rgba(15, 23, 42, 0.22); }
        @media (max-width: 640px) { .app-shell { padding: 0; } .app-container { width: 100vw; height: 100vh; border-radius: 0; } }
    </style>
</head>
<body class="app-page">
<div id="root"></div>

@verbatim
    <script type="text/babel">
        const { useState, useEffect, useMemo } = React;

        const Ico = ({ n, fill=false, size=24, style={} }) => (
            <span className={`ms ${fill?'ms-fill':''}`} style={{fontSize:size,lineHeight:1,...style}}>{n}</span>
        );

        const getCsrfToken = () => document.querySelector('meta[name="csrf-token"]').getAttribute('content');

        // Parse pack data from Laravel
        const pack = JSON.parse(document.getElementById('pack-data').textContent);

        const ProductSelectionScreen = () => {
            const [products, setProducts] = useState({});
            const [selectedProducts, setSelectedProducts] = useState([]);
            const [loading, setLoading] = useState(false);
            const [fetching, setFetching] = useState(true);

            // Check if user has discount based on the data passed from the controller
            const isRedbankUser = pack.hasRedbankDiscount === true;

            useEffect(() => {
                fetch('/api/products')
                    .then(res => res.json())
                    .then(data => {
                        if(data.success) {
                            setProducts(data.products);

                            // Auto-select the first mandatory product by default to save user a click
                            if(data.products.dress && data.products.dress.length > 0) {
                                setSelectedProducts([data.products.dress[0].id]);
                            }
                        }
                        setFetching(false);
                    });
            }, []);

            const toggleProduct = (productId, category, isMandatory) => {
                setSelectedProducts(prev => {
                    if (isMandatory) {
                        const otherCategoryItems = prev.filter(id => !products[category].find(p => p.id === id));
                        return [...otherCategoryItems, productId];
                    }
                    return prev.includes(productId)
                        ? prev.filter(id => id !== productId)
                        : [...prev, productId];
                });
            };

            const submitStep1 = async () => {
                setLoading(true);
                try {
                    const res = await fetch('/api/enrollment/draft', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': getCsrfToken() },
                        body: JSON.stringify({
                            pack_id: pack.id,
                            selected_products: selectedProducts
                        })
                    });
                    const data = await res.json();

                    if (data.success) {
                        window.location.href = `/enrollment/checkout/${data.tracking_id}`;
                    } else {
                        alert(data.message);
                        setLoading(false);
                    }
                } catch (e) {
                    alert('خطا در ارتباط با سرور');
                    setLoading(false);
                }
            };

            // Calculate Subtotal (Price before any discount)
            const subTotal = useMemo(() => {
                let itemsSum = 0;
                Object.values(products).forEach(cat => {
                    cat.forEach(p => {
                        if (selectedProducts.includes(p.id)) itemsSum += parseFloat(p.price);
                    });
                });
                return parseFloat(pack.price || 0) + itemsSum;
            }, [selectedProducts, products]);

            // Calculate final total with 10% discount if applicable
            const discountAmount = isRedbankUser ? subTotal * 0.10 : 0;
            const finalTotal = subTotal - discountAmount;

            if (fetching) return (
                <div className="absolute inset-0 bg-[#F5F7FA] flex items-center justify-center flex-col gap-3">
                    <div className="w-8 h-8 border-4 border-[#D32F2F] border-t-transparent rounded-full animate-spin"></div>
                    <div className="text-sm font-bold text-[#102A43]">در حال بارگذاری اطلاعات...</div>
                </div>
            );

            return (
                <div className="absolute inset-0 bg-[#F5F7FA] flex flex-col">
                    <header className="h-14 bg-white border-b border-gray-100 shadow-sm flex items-center justify-between px-4 shrink-0 z-10">
                        <button onClick={() => window.history.back()} className="w-10 h-10 flex items-center justify-center rounded-full hover:bg-gray-50 transition-colors">
                            <Ico n="arrow_forward" style={{color:'#D32F2F'}}/>
                        </button>
                        <h1 className="font-bold text-sm text-[#102A43]">انتخاب تجهیزات</h1>
                        <div className="w-10"/>
                    </header>

                    <div className="flex-1 overflow-y-auto px-4 py-5 flex flex-col gap-6 pb-36 hide-sb">

                        {/* 1. Pack Summary Section */}
                        <section className="fade-up" style={{animationDelay: '0s'}}>
                            <h2 className="font-black text-sm text-[#102A43] mb-3">دوره انتخابی شما</h2>
                            <div className="bg-white rounded-2xl p-4 shadow-sm border border-gray-100 flex flex-col gap-3 relative overflow-hidden">
                                <div className="absolute -left-4 -bottom-4 opacity-[0.03]">
                                    <Ico n="sports_soccer" size={100} style={{color:'#102A43'}}/>
                                </div>
                                <div className="flex gap-3 items-center z-10">
                                    <div className="w-12 h-12 rounded-xl bg-[#fff0ef] flex items-center justify-center shrink-0">
                                        <Ico n="calendar_today" fill size={22} style={{color:'#D32F2F'}}/>
                                    </div>
                                    <div className="flex-1">
                                        <p className="text-[10px] font-black text-[#486581] uppercase tracking-widest mb-1">{pack.schoolName || 'آکادمی فوتبال'}</p>
                                        <h3 className="font-bold text-sm text-[#102A43]">{pack.title || pack.packName || 'نام دوره'}</h3>
                                    </div>
                                </div>
                                <div className="border-t border-dashed border-gray-100 mt-1 pt-3 z-10 flex justify-between items-center">
                                    <span className="text-xs text-[#486581]">هزینه پایه کلاس (امکان پرداخت در 4 قسط):</span>
                                    <span className="font-bold text-sm text-[#102A43]">
                                        {parseFloat(pack.price).toLocaleString()} <span className="text-[10px] font-normal">تومان</span>
                                    </span>
                                </div>
                            </div>
                        </section>

                        {/* 2. Products Iteration */}
                        {Object.keys(products).map((category, index) => {
                            const isDress = category === 'dress';
                            return (
                                <section key={category} className="fade-up" style={{animationDelay: `${(index + 1) * 0.1}s`}}>
                                    <div className="flex justify-between items-end mb-3">
                                        <h2 className="font-black text-sm text-[#102A43]">
                                            {isDress ? 'انتخاب کیت ورزشی' : 'تجهیزات جانبی'}
                                        </h2>
                                        <span className={`text-[10px] font-bold px-2 py-0.5 rounded-lg ${isDress ? 'bg-[#fff0ef] text-[#D32F2F]' : 'bg-gray-200 text-[#486581]'}`}>
                                            {isDress ? 'انتخاب الزامی' : 'اختیاری'}
                                        </span>
                                    </div>

                                    <div className="flex flex-col gap-3">
                                        {products[category].map(item => {
                                            const isSelected = selectedProducts.includes(item.id);
                                            return (
                                                <label key={item.id} className={`flex gap-3 p-3.5 rounded-2xl border-2 cursor-pointer transition-all ${isSelected ? 'border-[#D32F2F] bg-[#fff8f7] shadow-sm' : 'border-gray-100 bg-white hover:border-gray-200'}`}>
                                                    <input
                                                        type="checkbox"
                                                        className="hidden"
                                                        checked={isSelected}
                                                        onChange={() => toggleProduct(item.id, category, item.is_mandatory)}
                                                    />

                                                    {/* Product Icon based on category */}
                                                    <div className={`w-10 h-10 rounded-full flex items-center justify-center shrink-0 transition-colors ${isSelected ? 'bg-[#D32F2F] text-white' : 'bg-gray-100 text-[#486581]'}`}>
                                                        <Ico n={isDress ? 'checkroom' : 'backpack'} size={20} />
                                                    </div>

                                                    <div className="flex-1 flex flex-col justify-center">
                                                        <p className={`font-bold text-sm transition-colors ${isSelected ? 'text-[#D32F2F]' : 'text-[#102A43]'}`}>{item.name}</p>
                                                        <p className="text-[11px] text-[#486581] mt-1 leading-relaxed">
                                                            {isDress
                                                                ? 'شامل پیراهن، شورت ورزشی و جوراب با لوگوی آکادمی'
                                                                : 'تجهیزات استاندارد با بالاترین کیفیت برای تمرینات'}
                                                        </p>
                                                        <div className="font-bold text-xs text-[#102A43] mt-2">
                                                            + {parseFloat(item.price).toLocaleString()} تومان
                                                        </div>
                                                    </div>

                                                    {/* Custom Checkbox UI */}
                                                    <div className={`w-6 h-6 rounded-full border-2 flex items-center justify-center shrink-0 mt-2 transition-all ${isSelected ? 'border-[#D32F2F] bg-[#D32F2F]' : 'border-gray-300 bg-white'}`}>
                                                        {isSelected && <Ico n="check" size={16} style={{color:'white'}}/>}
                                                    </div>
                                                </label>
                                            );
                                        })}
                                    </div>
                                </section>
                            );
                        })}
                    </div>

                    {/* Fixed Bottom Action Bar */}
                    <div className="absolute bottom-0 right-0 w-full px-4 pb-6 pt-4 bg-white border-t border-gray-100 shadow-[0_-12px_30px_rgba(0,0,0,0.06)] z-20 fade-up" style={{animationDelay: '0.4s'}}>

                        {/* Show Discount Banner if user is Red Bank */}
                        {isRedbankUser && (
                            <div className="flex items-center gap-2 bg-[#e8f5e9] border border-[#c8e6c9] text-[#2E7D32] px-3 py-2 rounded-xl mb-3 fade-up" style={{animationDelay: '0.5s'}}>
                                <Ico n="verified" size={18} fill />
                                <span className="text-[11px] font-bold">شما دارای ۱۰٪ تخفیف ویژه «رد بانک» هستید!</span>
                            </div>
                        )}

                        <div className="flex justify-between items-end mb-3 px-1">
                            <div className="flex flex-col">
                                <span className="font-bold text-xs text-[#486581]">مبلغ نهایی پرداخت :</span>
                                {isRedbankUser && (
                                    <span className="text-[10px] text-gray-400 line-through mt-0.5">
                                        {subTotal.toLocaleString()} تومان
                                    </span>
                                )}
                            </div>
                            <div className="flex flex-col items-end">
                                <span className="font-black text-xl text-[#D32F2F] leading-none">
                                    {finalTotal.toLocaleString()} <span className="text-xs font-normal text-[#486581] mr-0.5">تومان</span>
                                </span>
                            </div>
                        </div>
                        <button disabled={loading} onClick={submitStep1} className="w-full h-14 bg-[#102A43] text-white rounded-xl font-bold text-sm flex items-center justify-center gap-2 shadow-lg shadow-slate-200 active:scale-[0.98] transition-all disabled:opacity-70 disabled:active:scale-100 hover:bg-[#1a3b5c]">
                            {loading ? 'در حال ثبت اطلاعات...' : 'تایید تجهیزات و ادامه به پرداخت'}
                            {!loading && <Ico n="arrow_back" size={18} style={{transform:'scaleX(-1)'}}/>}
                        </button>
                    </div>
                </div>
            );
        };

        const App = () => (
            <div className="app-shell">
                <div className="app-container">
                    <ProductSelectionScreen />
                </div>
            </div>
        );

        ReactDOM.createRoot(document.getElementById('root')).render(<App/>);
    </script>
@endverbatim

<script type="application/json" id="pack-data">
    {!! json_encode($packData) !!}
</script>

</body>
</html>
