<!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 — Login</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-feature-settings: 'liga'; font-feature-settings: 'liga'; -webkit-font-smoothing: antialiased; user-select: none; }
        .ms-fill { font-variation-settings: 'FILL' 1,'wght' 400,'GRAD' 0,'opsz' 24; }
        .hide-sb::-webkit-scrollbar { display: none; }
        .hide-sb { -ms-overflow-style: none; scrollbar-width: none; }
        @keyframes fadeUp { from { opacity:0; transform:translateY(12px); } to { opacity:1; transform:translateY(0); } }
        @keyframes pop { 0%{transform:scale(0.85);opacity:0} 60%{transform:scale(1.05)} 100%{transform:scale(1);opacity:1} }
        @keyframes slide { from{opacity:0;transform:translateX(-16px)} to{opacity:1;transform:translateX(0)} }
        .fade-up { animation: fadeUp 0.3s ease both; }
        .pop-in { animation: pop 0.4s cubic-bezier(.34,1.56,.64,1) both; }
        .slide-in { animation: slide 0.25s ease both; }
        html { min-height: 100%; }
        .app-page {
            min-height: 100vh;
            min-height: 100dvh;
            margin: 0;
            background: #eef2f7;
        }
        .app-shell {
            width: 100%;
            min-height: 100vh;
            min-height: 100dvh;
            padding: 24px;
            display: grid;
            place-items: center;
        }
        .app-container {
            position: relative;
            width: min(100%, 430px);
            height: min(844px, calc(100vh - 48px));
            height: min(844px, calc(100dvh - 48px));
            min-height: min(640px, calc(100vh - 48px));
            min-height: min(640px, calc(100dvh - 48px));
            overflow: hidden;
            background: #F5F7FA;
            border-radius: 28px;
            box-shadow: 0 28px 80px rgba(15, 23, 42, 0.22), 0 4px 18px rgba(15, 23, 42, 0.08);
        }
        .app-container button {
            transition-property: translate, transform, box-shadow, background-color, border-color, color, opacity;
            transition-duration: 180ms;
            transition-timing-function: ease;
        }
        .app-container button:disabled { translate: none; transform: none; opacity: 0.7; }
        @media (hover: hover) {
            .app-container button:not(:disabled):hover { translate: 0 -1px; }
        }
        @media (min-width: 768px) {
            .app-shell { padding: 32px; }
            .app-container {
                width: min(430px, calc(100vw - 64px));
                height: min(844px, calc(100vh - 64px));
                height: min(844px, calc(100dvh - 64px));
                min-height: min(680px, calc(100vh - 64px));
                min-height: min(680px, calc(100dvh - 64px));
            }
        }
        @media (max-width: 640px) {
            .app-shell { min-height: 100vh; min-height: 100dvh; padding: 0; display: block; }
            .app-container {
                width: 100vw;
                height: 100vh;
                height: 100dvh;
                min-height: 100vh;
                min-height: 100dvh;
                border-radius: 0;
                box-shadow: none;
            }
        }
    </style>
</head>
<body class="app-page">
<div id="root"></div>

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

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

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

        /* ────────────────────────────────────────────
           SCREEN 1 — LOGIN
        ──────────────────────────────────────────── */
        const LoginScreen = ({ go, setGlobalPhone }) => {
            const [phone, setPhone] = useState('');
            const [err, setErr] = useState('');
            const [loading, setLoading] = useState(false);
            const [msg, setMsg] = useState('');

            const handlePhone = e => {
                const v = e.target.value.replace(/\D/g,'').slice(0,11);
                setPhone(v);
                setErr('');
            };

            const submit = async () => {
                if(phone.length !== 11 || !phone.startsWith('09')){
                    setErr('شماره موبایل معتبر نیست (مثال: 09123456789)');
                    return;
                }

                setLoading(true);
                setErr('');
                setMsg('');

                try {
                    const res = await fetch('/login/send-otp', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': getCsrfToken(),
                            'Accept': 'application/json'
                        },
                        body: JSON.stringify({ phone })
                    });

                    const data = await res.json();

                    if (res.ok && data.success) {
                        setGlobalPhone(phone); // Save phone in app state
                        // Optional: show a message like "Test Code: 123456" for dev
                        console.log(data.message);
                        go('otp');
                    } else {
                        setErr(data.message || 'خطایی رخ داد.');
                    }
                } catch (error) {
                    setErr('خطا در ارتباط با سرور.');
                } finally {
                    setLoading(false);
                }
            };

            const valid = phone.length === 11 && !loading;

            return (
                <div className="absolute inset-0 bg-[#F5F7FA] flex flex-col slide-in">
                    <div className="bg-[#D32F2F] h-52 flex items-center justify-center relative overflow-hidden shrink-0 rounded-b-[2rem]">
                        <div className="absolute inset-0 bg-gradient-to-br from-[#D32F2F] to-[#8B0000]"/>
                        <div className="absolute -top-10 -left-10 w-40 h-40 rounded-full bg-white/5"/>
                        <div className="absolute -bottom-8 -right-8 w-32 h-32 rounded-full bg-white/5"/>
                        <div className="relative z-10 flex flex-col items-center">
                            <div className="w-14 h-14 rounded-full bg-white/20 flex items-center justify-center mb-3">
                                <Ico n="sports_soccer" fill size={32} cls="text-white"/>
                            </div>
                            <h1 className="text-3xl font-black text-white uppercase tracking-tight">Red Talent</h1>
                            <p className="text-white/70 text-xs mt-1">آکادمی فوتبال پرسپولیس</p>
                        </div>
                    </div>

                    <div className="flex-1 overflow-y-auto px-5 pt-7 pb-6 flex flex-col gap-5">
                        <div className="text-center fade-up">
                            <h2 className="text-xl font-bold text-[#102A43]">خوش آمدید</h2>
                            <p className="text-[#486581] text-sm mt-1">شماره موبایل خود را وارد کنید تا وارد شوید یا ثبت‌نام کنید</p>
                        </div>

                        <div className="flex flex-col gap-1.5 fade-up" style={{animationDelay:'0.05s'}}>
                            <label className="text-[10px] font-bold text-[#102A43] uppercase tracking-widest">شماره موبایل</label>
                            <div className="relative">
            <span className="absolute right-3.5 top-1/2 -translate-y-1/2 pointer-events-none">
              <Ico n="phone_iphone" size={20} style={{color:'#486581'}}/>
            </span>
                                <input type="tel" inputMode="numeric" dir="ltr"
                                       value={phone} onChange={handlePhone} placeholder="09XX XXX XXXX" disabled={loading}
                                       className={`w-full h-12 pr-11 pl-4 rounded-xl border-2 bg-white text-[#102A43] font-semibold text-base text-left focus:outline-none transition-all placeholder:text-gray-300 placeholder:font-normal ${err?'border-red-400 bg-red-50':'border-gray-200 focus:border-[#D32F2F]'}`}/>
                            </div>
                            {err && (
                                <div className="flex items-center gap-1 text-red-600 text-xs fade-up">
                                    <Ico n="error" fill size={14}/>
                                    <span>{err}</span>
                                </div>
                            )}
                        </div>

                        <button onClick={submit} disabled={!valid}
                                className={`w-full h-12 rounded-xl font-bold text-base flex items-center justify-center gap-2 transition-all active:scale-[0.97] fade-up ${valid?'bg-[#D32F2F] text-white shadow-lg shadow-red-200 hover:bg-[#b71c1c]':'bg-gray-200 text-gray-400 cursor-not-allowed'}`}
                                style={{animationDelay:'0.1s'}}>
                            {loading ? 'در حال ارسال...' : 'ارسال کد تأیید'}
                            {!loading && <Ico n="arrow_back" size={20} style={{transform:'scaleX(-1)'}} cls="text-current"/>}
                        </button>

                        <p className="text-center text-xs text-[#486581]/60 mt-auto fade-up" style={{animationDelay:'0.15s'}}>
                            با ادامه، <span className="text-[#D32F2F] font-semibold cursor-pointer">شرایط استفاده</span> و <span className="text-[#D32F2F] font-semibold cursor-pointer">حریم خصوصی</span> را می‌پذیرید.
                        </p>
                    </div>
                </div>
            );
        };

        /* ────────────────────────────────────────────
           SCREEN 2 — OTP
        ──────────────────────────────────────────── */
        const OTPScreen = ({ go, phone }) => {
            const [digits, setDigits] = useState(Array(6).fill(''));
            const [timer, setTimer] = useState(120);
            const [err, setErr] = useState('');
            const [success, setSuccess] = useState(false);
            const [loading, setLoading] = useState(false);
            const refs = useRef([]);

            useEffect(() => {
                if(timer <= 0) return;
                const t = setInterval(()=>setTimer(p=>p-1), 1000);
                return ()=>clearInterval(t);
            },[timer]);

            const verifyCode = async (codeStr) => {
                setLoading(true);
                setErr('');

                try {
                    const res = await fetch('/login/verify', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': getCsrfToken(),
                            'Accept': 'application/json'
                        },
                        body: JSON.stringify({ phone: phone, code: codeStr })
                    });

                    const data = await res.json();

                    if (res.ok && data.success) {
                        setSuccess(true);
                        setTimeout(() => window.location.href = data.redirect || '/dashboard', 700);
                    } else {
                        setErr(data.message || 'کد نامعتبر است.');
                        setDigits(Array(6).fill(''));
                        setTimeout(() => refs.current[0]?.focus(), 50);
                    }
                } catch (e) {
                    setErr('خطا در ارتباط با سرور.');
                } finally {
                    setLoading(false);
                }
            };

            const handleDigit = (i, v) => {
                const n = v.replace(/\D/g,'').slice(-1);
                const nd = [...digits];
                nd[i] = n;
                setDigits(nd);
                setErr('');

                if(n && i < 5) refs.current[i+1]?.focus();

                // Auto-submit when all 6 digits are filled
                if(i === 5 && n && !loading) {
                    const code = [...nd.slice(0,5), n].join('');
                    verifyCode(code);
                }
            };

            const handleKey = (i,e) => {
                if(e.key === 'Backspace' && !digits[i] && i > 0) refs.current[i-1]?.focus();
            };

            const fmt = s => `${String(Math.floor(s/60)).padStart(2,'0')}:${String(s%60).padStart(2,'0')}`;

            return (
                <div className="absolute inset-0 bg-[#F5F7FA] flex flex-col slide-in">
                    <header className="h-14 bg-white border-b border-gray-100 flex items-center px-4 shrink-0">
                        <button onClick={()=>go('login')} disabled={loading} className="w-10 h-10 flex items-center justify-center rounded-full hover:bg-gray-50 active:scale-90 transition-transform">
                            <Ico n="arrow_forward" style={{color:'#D32F2F'}}/>
                        </button>
                    </header>

                    <div className="flex-1 overflow-y-auto px-5 pt-8 pb-6 flex flex-col gap-6">
                        <div className="text-center fade-up">
                            <div className={`w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4 transition-colors ${success?'bg-green-100':'bg-[#ffe9e7]'}`}>
                                <Ico n={success?'check_circle':'shield_lock'} fill size={34} style={{color:success?'#2E7D32':'#D32F2F'}}/>
                            </div>
                            <h2 className="text-xl font-bold text-[#102A43]">تأیید هویت</h2>
                            <p className="text-[#486581] text-sm mt-2 leading-relaxed">کد ۶ رقمی ارسال‌شده به شماره موبایل شما را وارد کنید</p>
                            <p className="text-[#D32F2F] font-bold text-sm mt-1" dir="ltr">{phone}</p>
                        </div>

                        <div className="flex gap-2 justify-center fade-up" style={{animationDelay:'0.05s'}} dir="ltr">
                            {digits.map((d,i) => (
                                <input key={i} ref={el=>refs.current[i]=el}
                                       type="text" inputMode="numeric" maxLength={1} value={d}
                                       onChange={e=>handleDigit(i,e.target.value)}
                                       onKeyDown={e=>handleKey(i,e)}
                                       disabled={loading || success}
                                       className={`w-11 h-14 text-center text-2xl font-black rounded-xl border-2 outline-none transition-all
                ${err?'border-red-400 bg-red-50 text-red-600 animate-pulse':success?'border-green-500 bg-green-50 text-green-700':d?'border-[#D32F2F] bg-[#fff8f7] text-[#102A43]':'border-gray-200 bg-white text-[#102A43]'}
                focus:border-[#D32F2F] focus:shadow-sm`}/>
                            ))}
                        </div>

                        {err && <p className="text-center text-red-600 text-xs font-semibold fade-up">{err}</p>}

                        <button disabled={loading || success || digits.join('').length !== 6}
                                onClick={()=> verifyCode(digits.join(''))}
                                className="w-full h-12 bg-[#D32F2F] text-white rounded-xl font-bold text-base flex items-center justify-center gap-2 shadow-lg shadow-red-200 hover:bg-[#b71c1c] active:scale-[0.97] transition-all fade-up disabled:opacity-70 disabled:cursor-not-allowed"
                                style={{animationDelay:'0.1s'}}>
                            {loading ? 'در حال بررسی...' : 'تأیید و ورود'}
                            {!loading && <Ico n="arrow_back" size={20} style={{transform:'scaleX(-1)'}}/>}
                        </button>

                        <div className="text-center flex flex-col items-center gap-2 fade-up" style={{animationDelay:'0.15s'}}>
                            <p className="text-[#486581] text-sm">کد را دریافت نکردید؟</p>
                            <div className="flex items-center gap-1 text-[#102A43] font-bold" dir="ltr">
                                <Ico n="timer" size={18} style={{color:'#D32F2F'}}/>
                                <span className="text-base">{fmt(timer)}</span>
                            </div>
                            <button disabled={timer>0 || loading} onClick={()=>{
                                setTimer(120);
                                setDigits(Array(6).fill(''));
                                setErr('');
                                // Ideally call send-otp fetch again here!
                            }}
                                    className={`text-xs font-bold uppercase tracking-wide transition-colors ${timer===0 && !loading ?'text-[#D32F2F] hover:underline cursor-pointer':'text-gray-400 cursor-not-allowed'}`}>
                                ارسال مجدد کد
                            </button>
                        </div>
                    </div>
                </div>
            );
        };

        /* ────────────────────────────────────────────
           APP
        ──────────────────────────────────────────── */
        const App = () => {
            const [screen, setScreen] = useState('login');
            const [globalPhone, setGlobalPhone] = useState('');

            const go = useCallback(s => setScreen(s), []);

            const screenMap = {
                login: <LoginScreen go={go} setGlobalPhone={setGlobalPhone}/>,
                otp:   <OTPScreen go={go} phone={globalPhone}/>,
            };

            return (
                <div className="app-shell">
                    <div className="app-container">
                        <div className="absolute inset-0 overflow-hidden" key={screen}>
                            {screenMap[screen]}
                        </div>
                    </div>
                </div>
            );
        };

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