@extends('siswa.layout')

@section('content')

<div class="w-full min-h-[calc(100vh-120px)] flex items-start md:items-center
            py-6 px-3 sm:px-4 md:px-6 overflow-x-hidden">
    <div class="w-full max-w-5xl mx-auto">

        {{-- ── PAGE TITLE ── --}}
        <div class="mb-6 text-center">
            <!--<span class="inline-flex items-center gap-2 bg-blue-50 border border-blue-100-->
            <!--             text-blue-600 text-xs font-semibold uppercase tracking-widest-->
            <!--             px-4 py-1.5 rounded-full mb-3">-->
            <!--    <span class="w-1.5 h-1.5 bg-blue-400 rounded-full animate-pulse"></span>-->
            <!--    Pengaturan Akun Siswa-->
            <!--</span>-->
            <h1 class="text-2xl sm:text-3xl font-extrabold text-slate-800">Keamanan Akun</h1>
            <p class="text-sm text-slate-400 mt-1">Perbarui password dan verifikasi email kamu</p>
        </div>

        {{-- ── GRID CARD ── --}}
        {{-- Pakai md:grid-cols-2 bukan lg agar lebih cepat side-by-side --}}
        <div class="grid grid-cols-1 md:grid-cols-2
                    rounded-3xl overflow-hidden shadow-2xl shadow-slate-200/80
                    min-h-0">  {{-- min-h-0 penting agar grid tidak collapse --}}

            {{-- ============================================================ --}}
            {{-- ==================== KOLOM KIRI: PASSWORD ================== --}}
            {{-- ============================================================ --}}
            <div class="relative bg-white p-6 sm:p-8 flex flex-col gap-5
                        min-w-0 min-h-0">  {{-- min-w-0 cegah overflow merusak grid --}}

                {{-- Dekorasi --}}
                <div class="absolute top-0 left-0 w-48 h-48 bg-gradient-to-br
                            from-sky-50 to-transparent rounded-br-full pointer-events-none"></div>

                {{-- Header --}}
                <div class="relative flex flex-col items-center text-center gap-2 pb-5 border-b border-slate-100">
                    <div class="w-14 h-14 rounded-2xl bg-gradient-to-br from-sky-500 to-blue-600
                                flex items-center justify-center shadow-lg shadow-sky-200 mb-1">
                        <i data-lucide="key" class="w-6 h-6 text-black"></i>
                    </div>
                    <h2 class="text-xl sm:text-2xl font-bold text-slate-800">Ganti Password</h2>
                    <p class="text-xs text-slate-400 mb-10">Buat password baru yang kuat untuk akunmu</p>
                </div>

                {{-- Alert: Status Session --}}
                @if(session('status'))
                <div class="flex items-center gap-2.5 bg-green-50 border border-green-200
                            text-green-700 text-sm rounded-2xl px-4 py-3">
                    <i data-lucide="check-circle-2" class="w-4 h-4 shrink-0"></i>
                    <span>{{ session('status') }}</span>
                </div>
                @endif

                {{-- Alert: Errors --}}
                @if($errors->any())
                <div class="flex items-start gap-2.5 bg-red-50 border border-red-200
                            text-red-600 text-sm rounded-2xl px-4 py-3">
                    <i data-lucide="alert-circle" class="w-4 h-4 shrink-0 mt-0.5"></i>
                    <ul class="space-y-0.5">
                        @foreach($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
                @endif

                {{-- Alert: Email Status --}}
                @if($student->email_verified_at)
                <!--<div class="flex items-center gap-2.5 bg-sky-50 border border-sky-200-->
                <!--            text-sky-700 text-sm rounded-2xl px-4 py-3">-->
                <!--    <i data-lucide="shield-check" class="w-4 h-4 shrink-0"></i>-->
                <!--    <span>Email <strong>{{ $student->email }}</strong> sudah terverifikasi ✓</span>-->
                <!--</div>-->
                @elseif($student->email)
                <!--<div class="flex items-center gap-2.5 bg-amber-50 border border-amber-200-->
                <!--            text-amber-700 text-sm rounded-2xl px-4 py-3">-->
                    <!--<i data-lucide="alert-triangle" class="w-4 h-4 shrink-0"></i>-->
                    <!--<span>Email <strong>{{ $student->email }}</strong> belum diverifikasi</span>-->
                <!--</div>-->
                @endif

                {{-- Form Password --}}
                <form method="POST" action="{{ route('siswa.password.update') }}"
                      class="flex flex-col gap-4" id="passwordForm">
                    @csrf

                    {{-- Password Lama --}}
                    <div class="flex flex-col gap-1.5">
                        <label class="text-xs font-semibold text-slate-500 uppercase tracking-wider">
                            Password Lama
                        </label>
                        <div class="relative">
                            <span class="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400">
                                <!--<i data-lucide="lock" class="w-4 h-4"></i>-->
                            </span>
                            <input type="password" name="current_password"
                                placeholder="Masukkan password lama"
                                class="w-full border border-slate-200 bg-slate-50 focus:bg-white
                                       focus:border-sky-400 focus:ring-4 focus:ring-sky-50
                                       rounded-xl pl-10 pr-4 py-3 text-sm outline-none transition-all"
                                required>
                        </div>
                    </div>

                    {{-- Password Baru --}}
                    <div class="flex flex-col gap-1.5">
                        <label class="text-xs font-semibold text-slate-500 uppercase tracking-wider">
                            Password Baru
                        </label>
                        <div class="relative">
                            <span class="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400">
                                <!--<i data-lucide="key-round" class="w-4 h-4"></i>-->
                            </span>
                            <input type="password" name="password" id="newPassword"
                                placeholder="Min. 8 karakter"
                                class="w-full border border-slate-200 bg-slate-50 focus:bg-white
                                       focus:border-sky-400 focus:ring-4 focus:ring-sky-50
                                       rounded-xl pl-10 pr-4 py-3 text-sm outline-none transition-all"
                                required>
                        </div>
                        <div class="mt-1 space-y-1.5">
                            <div class="flex gap-1 h-1.5">
                                <div id="bar1" class="flex-1 rounded-full bg-slate-200 transition-all duration-300"></div>
                                <div id="bar2" class="flex-1 rounded-full bg-slate-200 transition-all duration-300"></div>
                                <div id="bar3" class="flex-1 rounded-full bg-slate-200 transition-all duration-300"></div>
                                <div id="bar4" class="flex-1 rounded-full bg-slate-200 transition-all duration-300"></div>
                            </div>
                            <p id="passwordStrength" class="text-xs font-semibold text-slate-400">
                                Kekuatan password: —
                            </p>
                        </div>
                    </div>

                    {{-- Konfirmasi --}}
                    <div class="flex flex-col gap-1.5">
                        <label class="text-xs font-semibold text-slate-500 uppercase tracking-wider">
                            Konfirmasi Password Baru
                        </label>
                        <div class="relative">
                            <span class="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-400">
                                <!--<i data-lucide="check-circle" class="w-4 h-4"></i>-->
                            </span>
                            <input type="password" name="password_confirmation"
                                placeholder="Ulangi password baru"
                                class="w-full border border-slate-200 bg-slate-50 focus:bg-white
                                       focus:border-sky-400 focus:ring-4 focus:ring-sky-50
                                       rounded-xl pl-10 pr-4 py-3 text-sm outline-none transition-all"
                                required>
                        </div>
                    </div>
                </form>

                {{-- Tips --}}
                <div class="bg-sky-50 border border-sky-100 rounded-2xl px-4 py-3
                            text-xs text-sky-700 space-y-1 mt-auto">
                    <p class="font-semibold flex items-center gap-1.5 mb-1">
                        <i data-lucide="shield" class="w-3.5 h-3.5"></i>
                        Tips Password Aman
                    </p>
                    <p>✓ Minimal 8 karakter</p>
                    <p>✓ Kombinasi huruf besar & angka</p>
                    <p>✓ Tambahkan simbol (!@#$%)</p>
                    <p>✓ Jangan pakai tanggal lahir atau nama</p>
                </div>
            </div>

            {{-- ============================================================ --}}
            {{-- ================ KOLOM KANAN: EMAIL OTP ==================== --}}
            {{-- ============================================================ --}}
            <div class="relative bg-gradient-to-br from-slate-900 via-blue-950 to-slate-900
                        p-6 sm:p-8 flex flex-col gap-6 min-w-0 min-h-0">

                <div class="absolute top-0 right-0 w-64 h-64 bg-sky-500/10 rounded-full
                            blur-3xl pointer-events-none"></div>
                <div class="absolute bottom-0 left-0 w-44 h-44 bg-blue-600/10 rounded-full
                            blur-2xl pointer-events-none"></div>

                {{-- Header --}}
                <div class="relative flex flex-col items-center text-center gap-2 pb-5 border-b border-white/10">
                    <div class="w-14 h-14 rounded-2xl bg-gradient-to-br from-sky-400 to-blue-600
                                flex items-center justify-center shadow-lg shadow-blue-900/50 mb-1">
                        <i data-lucide="mail" class="w-6 h-6 text-white"></i>
                    </div>
                    <h2 class="text-xl sm:text-2xl font-bold text-white">Verifikasi Email</h2>
                    <p class="text-xs text-slate-400">Konfirmasi identitas via kode OTP ke emailmu</p>
                </div>

                {{-- Step 1: Email --}}
                <div class="relative flex flex-col gap-3">
                    <div class="flex items-center gap-2 mb-1">
                        <span class="w-6 h-6 rounded-full bg-sky-500/20 border border-sky-500/40
                                     text-white text-xs font-bold flex items-center justify-center">1</span>
                        <label class="text-xs font-semibold text-slate-300 uppercase tracking-wider">
                            Email Aktif Kamu
                        </label>
                    </div>
                    <div class="flex gap-2">
                        <div class="relative flex-1 min-w-0">
                            <span class="absolute left-3.5 top-1/2 -translate-y-1/2 text-slate-500">
                                <!--<i data-lucide="at-sign" class="w-4 h-4"></i>-->
                            </span>
                            <input type="email" id="emailInput"
                                value="{{ $student->email }}"
                                placeholder="contoh@email.com"
                                class="w-full bg-white/5 border border-white/10 hover:border-white/20
                                       focus:border-sky-500 focus:ring-4 focus:ring-sky-500/20
                                       text-white placeholder-slate-600 rounded-xl
                                       pl-10 pr-4 py-3 text-sm outline-none transition-all"
                                required>
                        </div>
                        <button type="button" id="sendOtpBtn"
                            class="shrink-0 bg-sky-600 hover:bg-sky-500 active:scale-95
                                   text-white text-sm font-semibold px-4 py-3 rounded-xl
                                   transition-all shadow-lg shadow-sky-900/40 whitespace-nowrap">
                            Kirim OTP
                        </button>
                    </div>
                    <div id="emailStatus" class="text-xs min-h-[18px]"></div>
                </div>

                <div class="border-t border-white/5"></div>

                {{-- Step 2: OTP --}}
                <div id="otpSection"
                     class="flex flex-col gap-3 transition-all duration-300
                            {{ !$student->email ? 'opacity-40 pointer-events-none' : '' }}">

                    <div class="flex items-center gap-2 mb-1">
                        <span class="w-6 h-6 rounded-full bg-blue-500/20 border border-blue-500/40
                                     text-white text-xs font-bold flex items-center justify-center">2</span>
                        <label class="text-xs font-semibold text-slate-300 uppercase tracking-wider">
                            Masukkan Kode OTP
                        </label>
                    </div>

                    <div class="flex gap-2">
                        <input type="text" id="otpInput" maxlength="6"
                            placeholder="• • • • • •"
                            class="flex-1 min-w-0 bg-white/5 border border-white/10 hover:border-white/20
                                   focus:border-blue-400 focus:ring-4 focus:ring-blue-500/20
                                   text-white placeholder-slate-600 text-center text-xl font-bold
                                   tracking-[0.5em] rounded-xl px-4 py-3 outline-none transition-all">
                        <button type="button" id="verifyOtpBtn"
                            class="shrink-0 bg-slate-700 text-slate-400 text-sm font-semibold
                                   px-4 py-3 rounded-xl cursor-not-allowed transition-all"
                            disabled>
                            Verifikasi
                        </button>
                        <button type="button" id="resendOtpBtn"
                            class="shrink-0 bg-white/10 hover:bg-white/15 text-slate-300
                                   text-sm font-semibold px-4 py-3 rounded-xl transition-all hidden">
                            Kirim Ulang
                        </button>
                    </div>

                    <div id="otpStatus" class="text-xs min-h-[18px]"></div>

                    <div class="flex items-center gap-2 bg-white/5 border border-white/8 rounded-xl px-4 py-3">
                        <i data-lucide="clock" class="w-4 h-4 text-slate-400 shrink-0"></i>
                        <p class="text-xs text-slate-400">
                            OTP dikirim ke email dan berlaku
                            <span class="font-semibold text-slate-300">10 menit</span>.
                            Cek folder <span class="font-semibold text-slate-300">Spam</span>
                            jika tidak masuk inbox.
                        </p>
                    </div>
                </div>

                {{-- Progress --}}
                <div class="mt-auto pt-4 border-t border-white/5">
                    <div class="flex items-center gap-3">
                        <div class="flex-1 h-1 rounded-full bg-white/10">
                            <div id="progressBar"
                                 class="h-1 rounded-full bg-gradient-to-r from-sky-400 to-blue-500
                                        transition-all duration-500 w-0"></div>
                        </div>
                        <span id="progressText" class="text-[10px] text-slate-500 whitespace-nowrap">
                            0 / 2 langkah
                        </span>
                    </div>
                    <p class="text-[5px] text-white mt-2 text-center">
                        Password akan tersimpan setelah OTP berhasil diverifikasi
                    </p>
                </div>
            </div>

        </div>{{-- end grid --}}
    </div>
</div>

{{-- ================= SCRIPT AJAX (tidak ada perubahan logika) ================= --}}
<script>
document.addEventListener('DOMContentLoaded', () => {
    lucide.createIcons();

    const emailInput       = document.getElementById('emailInput');
    const otpInput         = document.getElementById('otpInput');
    const sendOtpBtn       = document.getElementById('sendOtpBtn');
    const verifyOtpBtn     = document.getElementById('verifyOtpBtn');
    const resendOtpBtn     = document.getElementById('resendOtpBtn');
    const emailStatus      = document.getElementById('emailStatus');
    const otpStatus        = document.getElementById('otpStatus');
    const otpSection       = document.getElementById('otpSection');
    const passwordForm     = document.getElementById('passwordForm');
    const passwordInput    = document.getElementById('newPassword');
    const passwordStrength = document.getElementById('passwordStrength');
    const progressBar      = document.getElementById('progressBar');
    const progressText     = document.getElementById('progressText');

    const setProgress = (s) => {
        progressBar.style.width = (s / 2 * 100) + '%';
        progressText.textContent = s + ' / 2 langkah';
    };

    passwordInput.addEventListener('input', () => {
        const value     = passwordInput.value;
        const hasSymbol = /[!@#$%^&*()]/.test(value);
        const hasNumber = /[0-9]/.test(value);
        const hasUpper  = /[A-Z]/.test(value);
        const minLength = value.length >= 8;
        const bars = ['bar1','bar2','bar3','bar4'].map(id => document.getElementById(id));
        bars.forEach(b => { b.className = 'flex-1 rounded-full bg-slate-200 transition-all duration-300'; });
        if (!value.length) {
            passwordStrength.textContent = 'Kekuatan password: —';
            passwordStrength.className = 'text-xs font-semibold text-slate-400';
            return;
        }
        if (minLength && hasSymbol && hasNumber && hasUpper) {
            bars.forEach(b => b.classList.add('bg-green-500'));
            passwordStrength.textContent = 'Kekuatan password: KUAT 💪';
            passwordStrength.className = 'text-xs font-semibold text-green-600';
        } else if (minLength && (hasNumber || hasUpper)) {
            [bars[0],bars[1],bars[2]].forEach(b => b.classList.add('bg-yellow-400'));
            passwordStrength.textContent = 'Kekuatan password: SEDANG ⚠️';
            passwordStrength.className = 'text-xs font-semibold text-yellow-500';
        } else {
            bars[0].classList.add('bg-red-500');
            passwordStrength.textContent = 'Kekuatan password: LEMAH ❌';
            passwordStrength.className = 'text-xs font-semibold text-red-500';
        }
    });

    otpInput.addEventListener('input', () => {
        if (otpInput.value.trim().length === 6) {
            verifyOtpBtn.disabled = false;
            verifyOtpBtn.className = 'shrink-0 bg-gradient-to-r from-sky-500 to-blue-600 ' +
                'hover:from-sky-400 hover:to-blue-500 active:scale-95 text-white ' +
                'text-sm font-semibold px-4 py-3 rounded-xl transition-all ' +
                'shadow-lg shadow-blue-900/40 cursor-pointer';
        } else {
            verifyOtpBtn.disabled = true;
            verifyOtpBtn.className = 'shrink-0 bg-slate-700 text-slate-400 text-sm ' +
                'font-semibold px-4 py-3 rounded-xl cursor-not-allowed transition-all';
        }
    });

    sendOtpBtn.addEventListener('click', async () => {

    const email = emailInput.value.trim();
    const currentPassword = document.querySelector('[name="current_password"]').value;

    if (!email) {
        emailStatus.innerHTML = '<span class="text-red-400">✗ Email harus diisi</span>';
        return;
    }

    if (!currentPassword) {
        emailStatus.innerHTML = '<span class="text-red-400">✗ Password lama harus diisi</span>';
        return;
    }

    sendOtpBtn.disabled = true;
    sendOtpBtn.textContent = '...';

    emailStatus.innerHTML = '<span class="text-slate-400">⏳ Mengecek password...</span>';

    try {

        // 🔐 CEK PASSWORD LAMA DULU
        const checkPassword = await fetch("{{ config('services.lms.api') }}/siswa/check-password", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer {{ session("token") }}',
                'Accept': 'application/json'
            },
            body: JSON.stringify({
                current_password: currentPassword
            })
        });

        const checkData = await checkPassword.json();

        if (!checkPassword.ok) {
            emailStatus.innerHTML = `<span class="text-red-400">✗ ${checkData.message}</span>`;
            sendOtpBtn.disabled = false;
            sendOtpBtn.textContent = 'Kirim OTP';
            return;
        }

        // ✅ PASSWORD BENAR → KIRIM OTP
        emailStatus.innerHTML = '<span class="text-slate-400">⏳ Mengirim OTP...</span>';

        const response = await fetch("{{ route('siswa.email.send') }}", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Accept': 'application/json'
            },
            body: JSON.stringify({ email })
        });

        const data = await response.json();

        if (response.ok) {
            emailStatus.innerHTML = '<span class="text-white">✓ OTP berhasil dikirim ke email</span>';

            otpSection.classList.remove('opacity-40', 'pointer-events-none');

            verifyOtpBtn.disabled = true;
            verifyOtpBtn.className =
                'shrink-0 bg-slate-700 text-slate-400 text-sm font-semibold px-4 py-3 rounded-xl cursor-not-allowed transition-all';

            verifyOtpBtn.textContent = 'Verifikasi';

            otpInput.value = '';
            otpInput.focus();

            setProgress(1);

        } else {
            emailStatus.innerHTML = `<span class="text-red-400">✗ ${data.message || 'Gagal mengirim OTP'}</span>`;
        }

    } catch (error) {

        emailStatus.innerHTML = '<span class="text-red-400">✗ Kesalahan jaringan</span>';

    } finally {

        sendOtpBtn.disabled = false;
        sendOtpBtn.textContent = 'Kirim OTP';

    }
});

    verifyOtpBtn.addEventListener('click', async () => {
        const otp = otpInput.value.trim();
        if (otp.length !== 6) { otpStatus.innerHTML = '<span class="text-red-400">✗ OTP harus 6 digit</span>'; return; }
        verifyOtpBtn.disabled = true;
        verifyOtpBtn.textContent = 'Memverifikasi...';
        otpStatus.innerHTML = '<span class="text-slate-400">⏳ Memverifikasi OTP...</span>';
        try {
            const response = await fetch("{{ route('siswa.email.verify') }}", {
                method: 'POST',
                headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Accept': 'application/json' },
                body: JSON.stringify({ otp })
            });
            const data = await response.json();
            if (response.ok) {
                otpStatus.innerHTML = '<span class="text-green-400">✓ Email berhasil diverifikasi! Mengganti password...</span>';
                otpInput.disabled = true;
                otpInput.value = '✓ ✓ ✓ ✓ ✓ ✓';
                verifyOtpBtn.innerHTML = '<span class="flex items-center gap-1"><i data-lucide="loader" class="w-4 h-4 animate-spin"></i> Menyimpan...</span>';
                resendOtpBtn.classList.add('hidden');
                setProgress(2);
                setTimeout(() => { passwordForm.submit(); }, 1000);
            } else {
                otpStatus.innerHTML = `<span class="text-red-400">✗ ${data.message || 'OTP tidak valid'}</span>`;
                otpInput.value = '';
                otpInput.focus();
                verifyOtpBtn.disabled = true;
                verifyOtpBtn.className = 'shrink-0 bg-slate-700 text-slate-400 text-sm font-semibold px-4 py-3 rounded-xl cursor-not-allowed transition-all';
                verifyOtpBtn.textContent = 'Verifikasi';
            }
        } catch {
            otpStatus.innerHTML = '<span class="text-red-400">✗ Kesalahan jaringan</span>';
            verifyOtpBtn.disabled = false;
            verifyOtpBtn.textContent = 'Verifikasi';
        }
    });

    resendOtpBtn.addEventListener('click', () => { sendOtpBtn.click(); });
    if (emailInput.value.trim()) { otpSection.classList.remove('opacity-40', 'pointer-events-none'); }
});
</script>

@endsection