<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cek Rekomendasi - ASGARD</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <style>
        body {
            font-family: 'Plus Jakarta Sans', sans-serif;
            background-color: #f8fafc;
        }

        .card-shadow {
            box-shadow: 0 14px 40px rgba(15, 23, 42, 0.08);
        }
    </style>
</head>
<body class="flex flex-col min-h-screen text-slate-800">

    <nav class="sticky top-0 z-50 bg-white/95 backdrop-blur-md border-b border-slate-100 px-6 py-4">
        <div class="max-w-7xl mx-auto flex items-center justify-between gap-4">
            <div class="flex items-center gap-4">
                <div class="w-10 h-10 bg-emerald-100 rounded-xl flex items-center justify-center text-emerald-600 font-bold">AS</div>
                <span class="font-black text-xl tracking-tighter text-emerald-950 uppercase italic">ASGARD.</span>
            </div>

            <div class="hidden md:flex items-center gap-8 text-[11px] font-bold uppercase tracking-widest text-slate-400">
                <a href="{{ route('student.profile') }}" class="hover:text-emerald-600 transition">Beranda</a>
                <a href="{{ route('student.prediction') }}" class="text-emerald-600">Cek Rekomendasi</a>
                <a href="#" class="hover:text-emerald-600 transition">Kontak BK</a>
            </div>

            <div class="flex items-center gap-3">
                <div class="hidden sm:flex items-center gap-3 bg-emerald-50 px-4 py-2 rounded-full border border-emerald-100">
                    <div class="w-2 h-2 bg-emerald-500 rounded-full animate-pulse"></div>
                    <span class="text-[10px] font-bold text-emerald-700 uppercase">Siswa Terdaftar</span>
                </div>
                <button onclick="handleLogout()" class="bg-red-50 hover:bg-red-100 text-red-600 border border-red-100 px-4 py-2 rounded-full transition-all">
                    <span class="text-[10px] font-bold uppercase tracking-widest">Logout</span>
                </button>
            </div>
        </div>
    </nav>

    <main class="flex-grow px-6 py-10">
        <div class="max-w-3xl mx-auto">
            <div class="bg-white rounded-[2rem] card-shadow border border-slate-100 px-6 md:px-10 py-8 md:py-10">
                <div class="text-center mb-8">
                    <div class="w-12 h-12 mx-auto rounded-2xl bg-emerald-100 flex items-center justify-center text-2xl mb-4">
                        🧠
                    </div>
                    <h1 class="text-3xl md:text-4xl font-extrabold tracking-tight text-slate-900">DIAGNOSIS JURUSAN</h1>
                    <p class="text-slate-500 mt-3 text-sm md:text-base">
                        Isi data berikut dengan jujur agar sistem dapat memberikan rekomendasi jurusan kuliah yang sesuai.
                    </p>
                </div>

                <div id="alert-box" class="hidden mb-6 rounded-2xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700"></div>

                <div class="space-y-6">
                    <section class="bg-slate-50 border border-slate-100 rounded-3xl p-5 md:p-6">
                        <h2 class="font-extrabold text-slate-800 mb-1">💰 Kondisi Ekonomi</h2>
                        <p class="text-sm text-slate-500 mb-4">
                            Masukkan estimasi pendapatan gabungan orang tua per bulan dalam rupiah.
                        </p>

                        <input
                            type="number"
                            id="gaji_ortu"
                            min="0"
                            placeholder="Contoh: 3000000"
                            class="w-full rounded-2xl border border-slate-200 bg-white px-4 py-4 text-base font-semibold text-slate-700 outline-none focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100"
                        >

                        <p class="text-xs text-slate-400 mt-2">
                            Isi dengan angka saja tanpa titik atau koma.
                        </p>
                    </section>

                    <section class="bg-emerald-50/40 border border-emerald-100 rounded-3xl p-5 md:p-6">
                        <h2 class="font-extrabold text-emerald-800 mb-4">🎯 Kuesioner Minat & Bakat</h2>

                        <div class="space-y-4">
                            <div>
                                <label for="q1" class="block text-sm font-semibold text-slate-700 mb-2">
                                    1. Aktivitas apa yang paling kamu sukai?
                                </label>
                                <select id="q1" class="question-select w-full rounded-2xl border border-slate-200 bg-white px-4 py-4 text-sm text-slate-700 outline-none focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100">
                                    <option value="">Pilih jawaban</option>
                                    <option value="r">Memperbaiki alat, praktik lapangan, atau pekerjaan teknis</option>
                                    <option value="i">Meneliti, mengamati, dan memecahkan masalah logika</option>
                                    <option value="a">Menggambar, menulis, mendesain, atau berkarya</option>
                                    <option value="s">Membantu, mengajar, atau mendampingi orang lain</option>
                                    <option value="e">Memimpin tim, negosiasi, atau berwirausaha</option>
                                    <option value="c">Mengatur data, arsip, dokumen, dan pekerjaan terstruktur</option>
                                </select>
                            </div>

                            <div>
                                <label for="q2" class="block text-sm font-semibold text-slate-700 mb-2">
                                    2. Saat ada tugas kelompok, kamu paling nyaman berperan sebagai apa?
                                </label>
                                <select id="q2" class="question-select w-full rounded-2xl border border-slate-200 bg-white px-4 py-4 text-sm text-slate-700 outline-none focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100">
                                    <option value="">Pilih jawaban</option>
                                    <option value="r">Pelaksana teknis atau praktik</option>
                                    <option value="i">Analis data dan pencari solusi</option>
                                    <option value="a">Pembuat ide dan desain</option>
                                    <option value="s">Penjaga kekompakan tim</option>
                                    <option value="e">Pemimpin dan presenter</option>
                                    <option value="c">Penyusun dokumen dan jadwal</option>
                                </select>
                            </div>

                            <div>
                                <label for="q3" class="block text-sm font-semibold text-slate-700 mb-2">
                                    3. Jenis pekerjaan masa depan yang paling menarik buatmu?
                                </label>
                                <select id="q3" class="question-select w-full rounded-2xl border border-slate-200 bg-white px-4 py-4 text-sm text-slate-700 outline-none focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100">
                                    <option value="">Pilih jawaban</option>
                                    <option value="r">Teknisi, operator, atau pekerjaan lapangan</option>
                                    <option value="i">Dokter, peneliti, analis, atau ilmuwan</option>
                                    <option value="a">Desainer, penulis, editor, atau seniman</option>
                                    <option value="s">Guru, konselor, perawat, atau pekerja sosial</option>
                                    <option value="e">Pebisnis, manajer, marketer, atau leader</option>
                                    <option value="c">Administrator, akuntan, atau staf operasional</option>
                                </select>
                            </div>

                            <div>
                                <label for="q4" class="block text-sm font-semibold text-slate-700 mb-2">
                                    4. Kegiatan sekolah seperti apa yang paling kamu nikmati?
                                </label>
                                <select id="q4" class="question-select w-full rounded-2xl border border-slate-200 bg-white px-4 py-4 text-sm text-slate-700 outline-none focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100">
                                    <option value="">Pilih jawaban</option>
                                    <option value="r">Praktikum, keterampilan, atau kegiatan teknis</option>
                                    <option value="i">Eksperimen, olimpiade, atau analisis kasus</option>
                                    <option value="a">Lomba desain, seni, atau karya kreatif</option>
                                    <option value="s">Kegiatan sosial, mentoring, atau organisasi pelayanan</option>
                                    <option value="e">OSIS, lomba bisnis, atau kepanitiaan inti</option>
                                    <option value="c">Administrasi acara, pencatatan, atau dokumentasi</option>
                                </select>
                            </div>

                            <div>
                                <label for="q5" class="block text-sm font-semibold text-slate-700 mb-2">
                                    5. Kamu paling nyaman bekerja dalam suasana seperti apa?
                                </label>
                                <select id="q5" class="question-select w-full rounded-2xl border border-slate-200 bg-white px-4 py-4 text-sm text-slate-700 outline-none focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100">
                                    <option value="">Pilih jawaban</option>
                                    <option value="r">Aktif, praktik, dan langsung di lapangan</option>
                                    <option value="i">Tenang, fokus, dan penuh analisis</option>
                                    <option value="a">Bebas, kreatif, dan tidak kaku</option>
                                    <option value="s">Hangat, kolaboratif, dan banyak interaksi</option>
                                    <option value="e">Dinamis, kompetitif, dan penuh tantangan</option>
                                    <option value="c">Rapi, teratur, dan jelas prosedurnya</option>
                                </select>
                            </div>
                        </div>
                    </section>

                    <section class="bg-slate-50 border border-slate-100 rounded-3xl p-5 md:p-6">
                        <h2 class="font-extrabold text-slate-700 mb-2">📚 Nilai Rapor</h2>
                        <p class="text-sm text-slate-500 mb-4">
                            Masukkan nilai rapor pada setiap mata pelajaran dengan rentang 0 sampai 100.
                        </p>

                        <div class="grid grid-cols-2 md:grid-cols-5 gap-4">
                            <div>
                                <label class="block text-xs font-bold text-slate-500 mb-2">Agama</label>
                                <input type="number" id="agama" min="0" max="100" placeholder="0 - 100" class="w-full rounded-xl border border-slate-200 bg-white px-3 py-3 font-semibold outline-none focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100">
                            </div>
                            <div>
                                <label class="block text-xs font-bold text-slate-500 mb-2">PKN</label>
                                <input type="number" id="pkn" min="0" max="100" placeholder="0 - 100" class="w-full rounded-xl border border-slate-200 bg-white px-3 py-3 font-semibold outline-none focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100">
                            </div>
                            <div>
                                <label class="block text-xs font-bold text-slate-500 mb-2">B. Indonesia</label>
                                <input type="number" id="bahasa_indonesia" min="0" max="100" placeholder="0 - 100" class="w-full rounded-xl border border-slate-200 bg-white px-3 py-3 font-semibold outline-none focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100">
                            </div>
                            <div>
                                <label class="block text-xs font-bold text-slate-500 mb-2">B. Inggris</label>
                                <input type="number" id="bahasa_inggris" min="0" max="100" placeholder="0 - 100" class="w-full rounded-xl border border-slate-200 bg-white px-3 py-3 font-semibold outline-none focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100">
                            </div>
                            <div>
                                <label class="block text-xs font-bold text-slate-500 mb-2">Matematika</label>
                                <input type="number" id="matematika" min="0" max="100" placeholder="0 - 100" class="w-full rounded-xl border border-slate-200 bg-white px-3 py-3 font-semibold outline-none focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100">
                            </div>

                            <div>
                                <label class="block text-xs font-bold text-slate-500 mb-2">Fisika</label>
                                <input type="number" id="fisika" min="0" max="100" placeholder="0 - 100" class="w-full rounded-xl border border-slate-200 bg-white px-3 py-3 font-semibold outline-none focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100">
                            </div>
                            <div>
                                <label class="block text-xs font-bold text-slate-500 mb-2">Kimia</label>
                                <input type="number" id="kimia" min="0" max="100" placeholder="0 - 100" class="w-full rounded-xl border border-slate-200 bg-white px-3 py-3 font-semibold outline-none focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100">
                            </div>
                            <div>
                                <label class="block text-xs font-bold text-slate-500 mb-2">Biologi</label>
                                <input type="number" id="biologi" min="0" max="100" placeholder="0 - 100" class="w-full rounded-xl border border-slate-200 bg-white px-3 py-3 font-semibold outline-none focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100">
                            </div>
                            <div>
                                <label class="block text-xs font-bold text-slate-500 mb-2">Sejarah</label>
                                <input type="number" id="sejarah" min="0" max="100" placeholder="0 - 100" class="w-full rounded-xl border border-slate-200 bg-white px-3 py-3 font-semibold outline-none focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100">
                            </div>
                            <div>
                                <label class="block text-xs font-bold text-slate-500 mb-2">Geografi</label>
                                <input type="number" id="geografi" min="0" max="100" placeholder="0 - 100" class="w-full rounded-xl border border-slate-200 bg-white px-3 py-3 font-semibold outline-none focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100">
                            </div>

                            <div>
                                <label class="block text-xs font-bold text-slate-500 mb-2">Ekonomi</label>
                                <input type="number" id="ekonomi_mapel" min="0" max="100" placeholder="0 - 100" class="w-full rounded-xl border border-slate-200 bg-white px-3 py-3 font-semibold outline-none focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100">
                            </div>
                            <div>
                                <label class="block text-xs font-bold text-slate-500 mb-2">Sosiologi</label>
                                <input type="number" id="sosiologi" min="0" max="100" placeholder="0 - 100" class="w-full rounded-xl border border-slate-200 bg-white px-3 py-3 font-semibold outline-none focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100">
                            </div>
                            <div>
                                <label class="block text-xs font-bold text-slate-500 mb-2">Seni Budaya</label>
                                <input type="number" id="seni_budaya" min="0" max="100" placeholder="0 - 100" class="w-full rounded-xl border border-slate-200 bg-white px-3 py-3 font-semibold outline-none focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100">
                            </div>
                            <div>
                                <label class="block text-xs font-bold text-slate-500 mb-2">PJOK</label>
                                <input type="number" id="pjok" min="0" max="100" placeholder="0 - 100" class="w-full rounded-xl border border-slate-200 bg-white px-3 py-3 font-semibold outline-none focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100">
                            </div>
                            <div>
                                <label class="block text-xs font-bold text-slate-500 mb-2">Informatika</label>
                                <input type="number" id="informatika" min="0" max="100" placeholder="0 - 100" class="w-full rounded-xl border border-slate-200 bg-white px-3 py-3 font-semibold outline-none focus:border-emerald-400 focus:ring-4 focus:ring-emerald-100">
                            </div>
                        </div>
                    </section>

                    <div class="flex flex-col sm:flex-row gap-3 pt-2">
                        <a href="{{ route('student.profile') }}"
                           class="w-full sm:w-1/3 text-center bg-slate-100 hover:bg-slate-200 text-slate-600 font-bold py-4 rounded-2xl transition">
                            Batal
                        </a>

                        <button id="btn-submit"
                                class="w-full sm:w-2/3 bg-emerald-600 hover:bg-emerald-700 text-white font-bold py-4 rounded-2xl transition shadow-lg shadow-emerald-200">
                            Cek Rekomendasi
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </main>

    <footer class="bg-[#062C22] text-white py-16 px-6 mt-16">
        <div class="max-w-7xl mx-auto grid grid-cols-1 md:grid-cols-3 gap-12">
            <div class="space-y-6">
                <div class="flex items-center gap-4">
                    <span class="font-black text-2xl tracking-tighter uppercase italic">ASGARD.</span>
                </div>
                <p class="text-slate-300 text-sm leading-relaxed max-w-xs">
                    Sistem pakar rekomendasi jurusan kuliah SMAN 4 Jember berbasis data-driven.
                </p>
            </div>

            <div>
                <h5 class="font-bold text-xs uppercase tracking-widest text-emerald-400 mb-6">Informasi</h5>
                <ul class="space-y-4 text-sm text-slate-300">
                    <li><a href="{{ route('panduan') }}" class="hover:text-white transition">Panduan Sistem</a></li>
                    <li><a href="#" class="hover:text-white transition">Kebijakan Privasi</a></li>
                </ul>
            </div>

            <div>
                <h5 class="font-bold text-xs uppercase tracking-widest text-emerald-400 mb-6">Sekolah</h5>
                <ul class="space-y-4 text-sm text-slate-300">
                    <li>SMAN 4 Jember</li>
                    <li>Jl. Wolter Monginsidi No.24</li>
                    <li>Jember, Jawa Timur</li>
                </ul>
            </div>
        </div>

        <div class="max-w-7xl mx-auto mt-16 pt-8 border-t border-white/10 text-center">
            <p class="text-[10px] font-medium uppercase tracking-[0.5em] text-slate-400">
                © 2026 GALANG SEFIAN ADJI - POLITEKNIK NEGERI JEMBER
            </p>
        </div>
    </footer>

    <script>
        const alertBox = document.getElementById('alert-box');
        const btnSubmit = document.getElementById('btn-submit');

        function showError(message) {
            alertBox.classList.remove('hidden');
            alertBox.textContent = message;
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }

        function hideError() {
            alertBox.classList.add('hidden');
            alertBox.textContent = '';
        }

        function getNumberValue(id) {
            return Number(document.getElementById(id).value || 0);
        }

        function getAccessToken() {
            return localStorage.getItem('access_token');
        }

        function getUserRole() {
            return localStorage.getItem('user_role');
        }

        function redirectByRole(role) {
            if (role === 'admin') {
                window.location.href = "{{ route('admin.dashboard') }}";
                return;
            }

            if (role === 'siswa') {
                window.location.href = "{{ route('student.profile') }}";
                return;
            }

            window.location.href = "{{ route('login') }}";
        }

        function validateForm(payload) {
            const scoreFields = [
                'agama', 'pkn', 'bahasa_indonesia', 'bahasa_inggris', 'matematika',
                'fisika', 'kimia', 'biologi', 'sejarah', 'geografi',
                'ekonomi_mapel', 'sosiologi', 'seni_budaya', 'pjok', 'informatika'
            ];

            for (const field of scoreFields) {
                const rawValue = document.getElementById(field).value;

                if (rawValue === '') {
                    return `Nilai ${field.replaceAll('_', ' ')} wajib diisi.`;
                }

                const value = Number(payload[field]);
                if (isNaN(value) || value < 0 || value > 100) {
                    return `Nilai ${field.replaceAll('_', ' ')} harus berada pada rentang 0 sampai 100.`;
                }
            }

            if (document.getElementById('gaji_ortu').value === '') {
                return 'Pendapatan gabungan orang tua wajib diisi.';
            }

            if (Number(payload.gaji_ortu) < 0) {
                return 'Pendapatan gabungan orang tua tidak boleh bernilai negatif.';
            }

            const questionIds = ['q1', 'q2', 'q3', 'q4', 'q5'];
            for (const id of questionIds) {
                if (!document.getElementById(id).value) {
                    return 'Semua pertanyaan minat dan bakat wajib diisi.';
                }
            }

            return null;
        }

        function calculateRiasecScores() {
            const scores = { r: 0, i: 0, a: 0, s: 0, e: 0, c: 0 };
            const questionIds = ['q1', 'q2', 'q3', 'q4', 'q5'];

            questionIds.forEach(id => {
                const value = document.getElementById(id).value;
                if (value && scores.hasOwnProperty(value)) {
                    scores[value] += 20;
                }
            });

            return scores;
        }

        async function handleLogout() {
            const token = getAccessToken();

            if (token) {
                try {
                    await fetch('/api/logout', {
                        method: 'POST',
                        headers: {
                            'Authorization': `Bearer ${token}`,
                            'Accept': 'application/json'
                        }
                    });
                } catch (error) {
                    console.error('Logout error:', error);
                }
            }

            localStorage.removeItem('access_token');
            localStorage.removeItem('user_role');
            window.location.href = "{{ route('login') }}";
        }

        document.addEventListener('DOMContentLoaded', function () {
            const token = getAccessToken();
            const role = getUserRole();

            if (!token) {
                window.location.href = "{{ route('login') }}";
                return;
            }

            if (role !== 'siswa') {
                redirectByRole(role);
            }
        });

        btnSubmit.addEventListener('click', async function () {
            hideError();

            const token = getAccessToken();
            const role = getUserRole();

            if (!token) {
                showError('Sesi login tidak ditemukan. Silakan login kembali.');
                setTimeout(() => {
                    window.location.href = "{{ route('login') }}";
                }, 1200);
                return;
            }

            if (role !== 'siswa') {
                redirectByRole(role);
                return;
            }

            btnSubmit.innerHTML = 'Memeriksa Rekomendasi...';
            btnSubmit.disabled = true;

            const scores = calculateRiasecScores();

            const payload = {
                agama: getNumberValue('agama'),
                pkn: getNumberValue('pkn'),
                bahasa_indonesia: getNumberValue('bahasa_indonesia'),
                bahasa_inggris: getNumberValue('bahasa_inggris'),
                matematika: getNumberValue('matematika'),
                fisika: getNumberValue('fisika'),
                kimia: getNumberValue('kimia'),
                biologi: getNumberValue('biologi'),
                sejarah: getNumberValue('sejarah'),
                geografi: getNumberValue('geografi'),
                ekonomi_mapel: getNumberValue('ekonomi_mapel'),
                sosiologi: getNumberValue('sosiologi'),
                seni_budaya: getNumberValue('seni_budaya'),
                pjok: getNumberValue('pjok'),
                informatika: getNumberValue('informatika'),
                riasec_r: scores.r,
                riasec_i: scores.i,
                riasec_a: scores.a,
                riasec_s: scores.s,
                riasec_e: scores.e,
                riasec_c: scores.c,
                gaji_ortu: getNumberValue('gaji_ortu')
            };

            const validationError = validateForm(payload);
            if (validationError) {
                showError(validationError);
                btnSubmit.innerHTML = 'Cek Rekomendasi';
                btnSubmit.disabled = false;
                return;
            }

            try {
                const response = await fetch('/api/student/proses-rekomendasi', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify(payload)
                });

                const result = await response.json();

                if (response.ok && result.success) {
                    window.location.href = result.redirect_url;
                    return;
                }

                if (response.status === 401) {
                    showError('Sesi login berakhir. Silakan login kembali.');
                    localStorage.removeItem('access_token');
                    localStorage.removeItem('user_role');

                    setTimeout(() => {
                        window.location.href = "{{ route('login') }}";
                    }, 1200);
                    return;
                }

                if (response.status === 403) {
                    showError(result.message || 'Anda tidak memiliki akses ke halaman ini.');
                    return;
                }

                showError(result.message || 'Terjadi kesalahan saat memproses rekomendasi.');
            } catch (error) {
                showError('Kesalahan jaringan. Pastikan Laravel dan API Flask sedang berjalan.');
            } finally {
                btnSubmit.innerHTML = 'Cek Rekomendasi';
                btnSubmit.disabled = false;
            }
        });
    </script>
</body>
</html>