<div class="container py-4">
    <!-- Breadcrumb -->
    <nav aria-label="breadcrumb" class="mb-4">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="<?= APP_URL ?>/scholarships" class="text-decoration-none">Intelligence Center</a></li>
            <li class="breadcrumb-item active" aria-current="page"><?= htmlspecialchars($scholarship['name']) ?></li>
        </ol>
    </nav>

    <div class="row g-4">
        <!-- Main Scholarship Info -->
        <div class="col-lg-8">
            <div class="card border-0 shadow-sm p-4 mb-4">
                <div class="d-flex justify-content-between align-items-start mb-3">
                    <div>
                        <span class="badge bg-success text-uppercase mb-2"><?= htmlspecialchars($scholarship['scholarship_type']) ?> Funding</span>
                        <h2 class="fw-bold font-outfit text-dark"><?= htmlspecialchars($scholarship['name']) ?></h2>
                        <p class="text-muted m-0">Provided by: <strong class="text-dark"><?= htmlspecialchars($scholarship['provider']) ?></strong></p>
                    </div>
                    <?php if (Auth::check()): ?>
                        <div>
                            <?php if ($is_saved): ?>
                                <form action="<?= APP_URL ?>/scholarships/<?= $scholarship['id'] ?>/unsave" method="POST" class="d-inline">
                                    <?= csrf_field() ?>
                                    <button type="submit" class="btn btn-warning rounded-pill px-4 shadow-sm font-outfit fw-bold"><i class="fa-solid fa-bookmark me-2"></i> Saved</button>
                                </form>
                            <?php else: ?>
                                <form action="<?= APP_URL ?>/scholarships/<?= $scholarship['id'] ?>/save" method="POST" class="d-inline">
                                    <?= csrf_field() ?>
                                    <button type="submit" class="btn btn-light rounded-pill px-4 shadow-sm font-outfit fw-bold"><i class="fa-regular fa-bookmark me-2"></i> Save</button>
                                </form>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                </div>

                <hr class="my-4 text-muted opacity-25">

                <h5 class="fw-bold font-outfit text-dark mb-3">Description</h5>
                <p class="text-muted leading-relaxed mb-4"><?= nl2br(htmlspecialchars($scholarship['description'] ?? '')) ?></p>

                <h5 class="fw-bold font-outfit text-dark mb-3">Eligibility Requirements</h5>
                <p class="text-muted leading-relaxed mb-4"><?= nl2br(htmlspecialchars($scholarship['eligibility_requirements'] ?? '')) ?></p>

                <h5 class="fw-bold font-outfit text-dark mb-3">Required Documents</h5>
                <p class="text-muted leading-relaxed mb-4"><?= nl2br(htmlspecialchars($scholarship['required_documents'] ?? '')) ?></p>
            </div>
            
            <!-- Linked Universities -->
            <?php if (!empty($scholarship['universities'])): ?>
                <div class="card border-0 shadow-sm p-4">
                    <h5 class="fw-bold font-outfit text-dark mb-3">Eligible Universities</h5>
                    <p class="text-muted text-xs mb-3">This scholarship can be utilized at the following universities:</p>
                    <div class="row g-3">
                        <?php foreach ($scholarship['universities'] as $uni): ?>
                            <div class="col-md-6">
                                <a href="<?= APP_URL ?>/universities/<?= $uni['slug'] ?>" class="text-decoration-none">
                                    <div class="border rounded p-3 d-flex align-items-center bg-light-subtle card-hover-effect">
                                        <i class="fa-solid fa-school text-primary fs-4 me-3"></i>
                                        <h6 class="fw-bold text-dark m-0"><?= htmlspecialchars($uni['name']) ?></h6>
                                    </div>
                                </a>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <!-- Sidebar Widget Column -->
        <div class="col-lg-4">
            <!-- Deadline & Apply Details Card -->
            <div class="card border-0 shadow-sm p-4 mb-4">
                <h5 class="fw-bold font-outfit text-dark mb-3">Details</h5>
                <ul class="list-unstyled text-sm mb-4">
                    <li class="d-flex justify-content-between mb-2">
                        <span class="text-muted">Funding Scope:</span>
                        <strong class="text-dark"><?= htmlspecialchars($scholarship['coverage']) ?></strong>
                    </li>
                    <li class="d-flex justify-content-between mb-2">
                        <span class="text-muted">Min WASSCE Grade:</span>
                        <strong class="text-dark">Aggregate <?= $scholarship['min_aggregate'] ?: 'None' ?></strong>
                    </li>
                    <li class="d-flex justify-content-between mb-2">
                        <span class="text-muted">Target Beneficiaries:</span>
                        <strong class="text-dark"><?= $scholarship['num_beneficiaries'] ?: 'N/A' ?> yearly</strong>
                    </li>
                    <li class="d-flex justify-content-between">
                        <span class="text-muted">Status:</span>
                        <?= statusBadge($scholarship['status']) ?>
                    </li>
                </ul>

                <div class="alert alert-danger border-0 text-center py-2 px-3 mb-4 rounded-3 text-xs">
                    <i class="fa-regular fa-clock me-2"></i> Application Deadline: <strong><?= formatDate($scholarship['application_deadline']) ?></strong>
                </div>

                <?php if ($scholarship['application_link']): ?>
                    <a href="<?= htmlspecialchars($scholarship['application_link']) ?>" target="_blank" class="btn btn-primary rounded-pill px-4 shadow-sm w-100 font-outfit fw-bold py-2"><i class="fa-solid fa-up-right-from-square me-2"></i>Apply Externally</a>
                <?php endif; ?>
            </div>

            <!-- SUCCESS PREDICTOR WIDGET -->
            <?php if (Auth::isStudent()): ?>
                <div class="card border-0 shadow-sm p-4 text-center" id="predictor-card">
                    <div class="badge-icon-box bg-success-subtle text-success rounded-circle mx-auto mb-3"><i class="fa-solid fa-chart-line fs-4"></i></div>
                    <h5 class="fw-bold font-outfit text-dark mb-2">AI Success Predictor</h5>
                    <p class="text-xs text-muted mb-4">Check your probability of getting this scholarship based on your current grades, financial need, and profile completeness.</p>
                    
                    <button class="btn btn-success rounded-pill px-4 w-100 font-outfit fw-bold py-2 shadow-sm" id="btn-predict">Calculate Probability</button>

                    <!-- Interactive result screen hidden initially -->
                    <div id="predict-result" style="display: none;" class="mt-4 border-top pt-4">
                        <div class="display-4 fw-extrabold font-outfit text-success mb-2" id="prob-percentage">0%</div>
                        <span class="badge bg-success px-3 py-1 rounded-pill mb-4" id="prob-label">High Chance</span>
                        
                        <div class="text-start mb-3">
                            <small class="text-muted text-xs fw-bold d-block mb-2">ELIGIBILITY ANALYSIS</small>
                            <ul class="list-unstyled text-xs text-muted" id="prob-reasons"></ul>
                        </div>

                        <div class="text-start" id="prob-improvements-box" style="display: none;">
                            <small class="text-danger text-xs fw-bold d-block mb-2">RECOMMENDED IMPROVEMENTS</small>
                            <ul class="list-unstyled text-xs text-danger" id="prob-improvements"></ul>
                        </div>
                    </div>
                </div>

                <script>
                document.addEventListener('DOMContentLoaded', function() {
                    const btn = document.getElementById('btn-predict');
                    const resultBox = document.getElementById('predict-result');
                    const percentage = document.getElementById('prob-percentage');
                    const label = document.getElementById('prob-label');
                    const reasonsList = document.getElementById('prob-reasons');
                    const improvementsBox = document.getElementById('prob-improvements-box');
                    const improvementsList = document.getElementById('prob-improvements');

                    btn.addEventListener('click', function() {
                        btn.disabled = true;
                        btn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Calculating...';

                        const formData = new FormData();
                        formData.append('scholarship_id', "<?= $scholarship['id'] ?>");

                        fetch(APP_URL + '/api/scholarship/predict', {
                            method: 'POST',
                            headers: {
                                'X-CSRF-Token': CSRF_TOKEN,
                                'X-Requested-With': 'XMLHttpRequest'
                            },
                            body: formData
                        })
                        .then(res => res.json())
                        .then(json => {
                            btn.style.display = 'none';
                            resultBox.style.display = 'block';

                            if (json.success && json.data) {
                                const data = json.data;
                                percentage.textContent = data.probability + '%';
                                percentage.className = 'display-4 fw-extrabold font-outfit text-' + data.color + ' mb-2';
                                label.textContent = data.label;
                                label.className = 'badge bg-' + data.color + ' px-3 py-1 rounded-pill mb-4';

                                // Render reasons
                                reasonsList.innerHTML = '';
                                data.reasons.forEach(r => {
                                    const li = document.createElement('li');
                                    li.className = 'mb-1';
                                    li.innerHTML = r;
                                    reasonsList.appendChild(li);
                                });

                                // Render improvements
                                if (data.improvements && data.improvements.length > 0) {
                                    improvementsBox.style.display = 'block';
                                    improvementsList.innerHTML = '';
                                    data.improvements.forEach(i => {
                                        const li = document.createElement('li');
                                        li.className = 'mb-1';
                                        li.innerHTML = '<i class="fa-solid fa-circle-exclamation me-1"></i> ' + i;
                                        improvementsList.appendChild(li);
                                    });
                                } else {
                                    improvementsBox.style.display = 'none';
                                }
                            } else {
                                percentage.textContent = 'Error';
                                label.textContent = 'Unable to predict';
                            }
                        })
                        .catch(err => {
                            btn.disabled = false;
                            btn.textContent = 'Calculate Probability';
                            alert('An error occurred during prediction.');
                            console.error(err);
                        });
                    });
                });
                </script>
            <?php endif; ?>
        </div>
    </div>
</div>
