<?php
declare(strict_types=1);

session_start();

if (!isset($_SESSION['student_id'])) {
    header('Location: student-login.php');
    exit;
}

require_once __DIR__ . '/../config/database.php';

$pdo = getDbConnection();
$studentId = (int)$_SESSION['student_id'];

function esStudentLearningGate(PDO $pdo, int $studentId): array
{
    $studentStmt = $pdo->prepare(
        "SELECT grade, class_name, academic_year_id
         FROM students
         WHERE id = ?
         LIMIT 1"
    );
    $studentStmt->execute([$studentId]);
    $student = $studentStmt->fetch(PDO::FETCH_ASSOC) ?: [];

    $grade = max(0, (int)($student['grade'] ?? 0));
    $className = trim((string)($student['class_name'] ?? ''));
    $academicYearId = max(0, (int)($student['academic_year_id'] ?? 0));

    return [
        'grade' => $grade,
        'is_managed' => ($className !== '' && $academicYearId > 0),
    ];
}

function esLevelCompleted(PDO $pdo, int $studentId, int $levelId): bool
{
    $stmt = $pdo->prepare(
        "SELECT
            COUNT(*) AS total_lessons,
            SUM(CASE WHEN scp.status = 'completed' THEN 1 ELSE 0 END) AS completed_lessons
         FROM lessons l
         INNER JOIN units u ON u.id = l.unit_id
         LEFT JOIN student_content_progress scp
           ON scp.student_id = ?
          AND scp.content_type = 'lesson'
          AND scp.content_id = l.id
         WHERE u.level_id = ?
           AND u.status = 'active'
           AND l.status = 'active'"
    );
    $stmt->execute([$studentId, $levelId]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];

    $total = (int)($row['total_lessons'] ?? 0);
    $completed = (int)($row['completed_lessons'] ?? 0);

    return $total > 0 && $completed >= $total;
}

function esOpenLevelIdsForBook(PDO $pdo, int $studentId, int $bookId): array
{
    $stmt = $pdo->prepare(
        "SELECT id
         FROM levels
         WHERE book_id = ?
           AND status = 'active'
         ORDER BY sort_order ASC, level_number ASC, id ASC"
    );
    $stmt->execute([$bookId]);
    $ids = array_map('intval', $stmt->fetchAll(PDO::FETCH_COLUMN));

    if ($ids === []) return [];

    $open = [$ids[0]];
    for ($i = 1, $count = count($ids); $i < $count; $i++) {
        if (esLevelCompleted($pdo, $studentId, $ids[$i - 1])) {
            $open[] = $ids[$i];
        } else {
            break;
        }
    }
    return $open;
}

function esCanAccessLevel(
    PDO $pdo,
    int $studentId,
    string $bookSlug,
    int $bookId,
    int $levelId,
    int $levelNumber,
    array $gate
): bool {
    if ($bookSlug === 'global-success' && !empty($gate['is_managed'])) {
        $grade = max(0, (int)($gate['grade'] ?? 0));
        return $grade > 0 && $levelNumber > 0 && $levelNumber <= $grade;
    }

    return in_array(
        $levelId,
        esOpenLevelIdsForBook($pdo, $studentId, $bookId),
        true
    );
}

$learningGate = esStudentLearningGate($pdo, $studentId);

/*
 * Trang Đang học:
 * student_learning_paths là nguồn chuẩn.
 * Mỗi Book + Level là một lộ trình riêng của học sinh.
 */
$pathsStmt = $pdo->prepare(
    "SELECT
        slp.id AS path_id,
        slp.book_id,
        slp.level_id,
        slp.last_unit_id,
        slp.last_lesson_id,
        slp.last_activity_id,
        slp.last_accessed_at,
        b.name AS book_name,
        b.slug AS book_slug,
        lv.name AS level_name,
        lv.slug AS level_slug,
        lv.level_number
     FROM student_learning_paths slp
     INNER JOIN books b
        ON b.id = slp.book_id
     INNER JOIN levels lv
        ON lv.id = slp.level_id
       AND lv.book_id = b.id
     WHERE slp.student_id = ?
       AND slp.is_active = 1
       AND b.status = 'active'
       AND lv.status = 'active'
     ORDER BY slp.last_accessed_at DESC, slp.id DESC"
);
$pathsStmt->execute([$studentId]);
$learningPaths = $pathsStmt->fetchAll(PDO::FETCH_ASSOC);

/*
 * student_learning_paths đã là nguồn chuẩn của tab Đang học.
 *
 * Quan trọng:
 * - Học sinh tự do có thể chọn một Level bắt đầu bất kỳ ở lần đầu.
 *   Vì vậy không được lọc path đó bằng quy tắc "chỉ mở từ Level đầu tiên",
 *   nếu không Up 1/Lớp 2 đã chọn hợp lệ sẽ bị biến mất khỏi tab Đang học.
 * - Với học sinh thuộc lớp giáo viên, chỉ Global Success mới bị giới hạn
 *   theo khối hiện tại. Everybody Up và sách khác vẫn theo learning path.
 */
$learningPaths = array_values(array_filter(
    $learningPaths,
    static function(array $path) use ($learningGate): bool {
        $bookSlug = (string)($path['book_slug'] ?? '');

        if ($bookSlug === 'global-success' && !empty($learningGate['is_managed'])) {
            $grade = max(0, (int)($learningGate['grade'] ?? 0));
            $levelNumber = max(0, (int)($path['level_number'] ?? 0));

            return $grade > 0
                && $levelNumber > 0
                && $levelNumber <= $grade;
        }

        return true;
    }
));

/*
 * Bổ sung Lesson hiện tại + tiến độ cho từng learning path.
 *
 * Đồng bộ với Home:
 * - trong từng Book + Level, tìm Lesson completed sau cùng;
 * - chọn Lesson kế tiếp ngay sau nó;
 * - nếu chưa có Lesson completed -> Lesson đầu tiên;
 * - nếu đã hoàn thành hết -> giữ Lesson cuối cùng để ôn.
 */
foreach ($learningPaths as &$path) {
    $path['current_lesson'] = null;
    $path['progress'] = 0;
    $path['continue_url'] = '';

    $lessonsStmt = $pdo->prepare(
        "SELECT
            l.id AS lesson_id,
            l.lesson_number,
            l.title AS lesson_title_text,
            l.unit_id,
            u.unit_number,
            u.title AS unit_title,
            CASE
                WHEN scp.status = 'completed' THEN 1
                ELSE 0
            END AS is_completed
         FROM lessons l
         INNER JOIN units u
            ON u.id = l.unit_id
         LEFT JOIN student_content_progress scp
            ON scp.student_id = ?
           AND scp.content_type = 'lesson'
           AND scp.content_id = l.id
         WHERE u.level_id = ?
           AND l.status = 'active'
           AND u.status = 'active'
         ORDER BY
            u.sort_order ASC,
            u.id ASC,
            l.sort_order ASC,
            l.id ASC"
    );
    $lessonsStmt->execute([
        $studentId,
        (int)$path['level_id'],
    ]);
    $levelLessons = $lessonsStmt->fetchAll(PDO::FETCH_ASSOC);

    if ($levelLessons !== []) {
        $lastCompletedIndex = null;

        foreach ($levelLessons as $index => $lessonRow) {
            if ((int)($lessonRow['is_completed'] ?? 0) === 1) {
                $lastCompletedIndex = $index;
            }
        }

        if ($lastCompletedIndex === null) {
            $targetIndex = 0;
        } elseif ($lastCompletedIndex + 1 < count($levelLessons)) {
            $targetIndex = $lastCompletedIndex + 1;
        } else {
            $targetIndex = $lastCompletedIndex;
        }

        $path['current_lesson'] = $levelLessons[$targetIndex];
        $lessonId = (int)$path['current_lesson']['lesson_id'];

        if ((int)($path['current_lesson']['is_completed'] ?? 0) === 1) {
            $path['progress'] = 100;
        } else {
            $totalStmt = $pdo->prepare(
                "SELECT COUNT(*)
                 FROM activities
                 WHERE lesson_id = ?
                   AND status = 'active'"
            );
            $totalStmt->execute([$lessonId]);
            $totalActivities = (int)$totalStmt->fetchColumn();

            $completedStmt = $pdo->prepare(
                "SELECT COUNT(DISTINCT scp.content_id)
                 FROM student_content_progress scp
                 INNER JOIN activities a
                    ON a.id = scp.content_id
                 WHERE scp.student_id = ?
                   AND scp.content_type = 'activity'
                   AND scp.status = 'completed'
                   AND a.lesson_id = ?
                   AND a.status = 'active'"
            );
            $completedStmt->execute([
                $studentId,
                $lessonId,
            ]);
            $completedActivities = (int)$completedStmt->fetchColumn();

            $path['progress'] = $totalActivities > 0
                ? (int)round(($completedActivities / $totalActivities) * 100)
                : 0;
        }

        $lessonNumber = trim((string)$path['current_lesson']['lesson_number']);
        $lessonForUrl = preg_match('/(\d+)/', $lessonNumber, $match)
            ? (int)$match[1]
            : $lessonNumber;

        $path['continue_url'] = 'student-activities.php?' . http_build_query([
            'book' => (string)$path['book_slug'],
            'level' => (string)$path['level_slug'],
            'level_id' => (int)$path['level_id'],
            'unit_id' => (int)$path['current_lesson']['unit_id'],
            'lesson_id' => $lessonId,
            'lesson' => $lessonForUrl,
        ]);
    } else {
        $path['continue_url'] = 'student-units.php?' . http_build_query([
            'book' => (string)$path['book_slug'],
            'level' => (string)$path['level_slug'],
            'level_id' => (int)$path['level_id'],
        ]);
    }
}

unset($path);

// Đưa sách đã có tiến độ học lên đầu; nếu nhiều sách cùng có tiến độ,
// ưu tiên sách được truy cập gần nhất.
usort($learningPaths, static function(array $a, array $b): int {
    $aHasLearning = !empty($a['current_lesson']) && (int)($a['progress'] ?? 0) > 0;
    $bHasLearning = !empty($b['current_lesson']) && (int)($b['progress'] ?? 0) > 0;

    if ($aHasLearning !== $bHasLearning) {
        return $aHasLearning ? -1 : 1;
    }

    return strcmp((string)($b['last_accessed_at'] ?? ''), (string)($a['last_accessed_at'] ?? ''));
});

$xpStmt = $pdo->prepare(
    "SELECT COALESCE(SUM(xp_change), 0)
     FROM xp_transactions
     WHERE student_id = ?"
);
$xpStmt->execute([$studentId]);
$totalXp = (int)$xpStmt->fetchColumn();

$pageTitle = '';
$pageSubtitle = '';
$activeStudentNav = 'learning';

include __DIR__ . '/../includes/student-layout-start.php';
?>

<style>
:root {
    --learning-bg: #eef7ff;
    --learning-surface: #ffffff;
    --learning-text: #17324d;
    --learning-muted: #6f8799;
    --learning-primary: #197fc4;
    --learning-primary-dark: #0b67ac;
    --learning-soft: #e7f4ff;
    --learning-border: #dbe9f3;
    --learning-shadow: 0 7px 22px rgba(29, 80, 116, .09);
    --learning-width: 520px;
    --learning-nav-height: 78px;
}

* {
    box-sizing: border-box;
}

html,
body {
    margin: 0 !important;
    min-height: 100%;
    background: var(--learning-bg) !important;
    color: var(--learning-text) !important;
    font-family: "Segoe UI", Tahoma, Arial, sans-serif !important;
}

body {
    padding-bottom: calc(
        var(--learning-nav-height)
        + env(safe-area-inset-bottom)
        + 16px
    ) !important;
}

/* Khung học sinh luôn giữ tỷ lệ mobile trên desktop. */
.student-app {
    width: min(100%, var(--learning-width)) !important;
    min-height: 100vh !important;
    margin: 0 auto !important;
    background: #f7fbff !important;
    box-shadow: 0 0 28px rgba(27, 73, 108, .08) !important;
}

/* Header mobile */
.student-header {
    position: sticky !important;
    top: 0 !important;
    z-index: 40 !important;
    display: grid !important;
    grid-template-columns: 46px minmax(0, 1fr) 46px !important;
    align-items: center !important;
    gap: 9px !important;
    min-height: 76px !important;
    padding: 12px 14px !important;
    background: linear-gradient(135deg, #3488ef, #17b8e4) !important;
    color: #ffffff !important;
    box-shadow: 0 5px 15px rgba(31, 135, 210, .22) !important;
}

.student-back {
    width: 44px !important;
    height: 44px !important;
    display: grid !important;
    place-items: center !important;
    border-radius: 50% !important;
    background: rgba(255,255,255,.15) !important;
    color: #ffffff !important;
    text-decoration: none !important;
    font-size: 27px !important;
    font-weight: 800 !important;
    box-shadow: none !important;
}

.student-header__text {
    min-width: 0 !important;
    text-align: center !important;
}

.student-header__text h1 {
    margin: 0 !important;
    color: #ffffff !important;
    font-size: 23px !important;
    font-weight: 850 !important;
    line-height: 1.15 !important;
}

.student-header__text p {
    margin: 4px 0 0 !important;
    overflow: hidden !important;
    color: rgba(255,255,255,.92) !important;
    font-size: 12.5px !important;
    white-space: nowrap !important;
    text-overflow: ellipsis !important;
}

.student-header__spacer {
    width: 44px !important;
    height: 44px !important;
}

.student-content {
    width: 100% !important;
    padding: 16px 14px 26px !important;
}

/* Intro */
.learning-intro {
    margin-bottom: 14px;
    padding: 15px 16px;
    border: 1px solid var(--learning-border);
    border-radius: 19px;
    background: linear-gradient(135deg, #edf6ff, #e6f1ff);
    box-shadow: var(--learning-shadow);
}

.learning-intro h2 {
    margin: 0;
    color: #123e62;
    font-size: 18px;
    line-height: 1.35;
}

.learning-intro p {
    margin: 6px 0 0;
    color: var(--learning-muted);
    font-size: 13px;
    line-height: 1.45;
}

/* Thẻ học tiếp */
.continue-card {
    align-items: start !important;
}

.continue-card .card__body {
    padding-top: 2px;
}

.continue-card__lesson {
    display: block;
    margin-top: 5px;
    color: var(--learning-text);
    font-size: 13px;
    font-weight: 800;
}

.continue-card__progress {
    display: flex;
    align-items: center;
    gap: 9px;
    margin-top: 10px;
}

.continue-card__track {
    flex: 1;
    height: 8px;
    overflow: hidden;
    border-radius: 999px;
    background: #dceaf5;
}

.continue-card__fill {
    height: 100%;
    border-radius: inherit;
    background: linear-gradient(90deg, #2584de, #20b2df);
}

.continue-card__percent {
    min-width: 38px;
    color: var(--learning-primary-dark);
    font-size: 12px;
    font-weight: 850;
    text-align: right;
}

/* Danh sách card */
.card-list {
    display: grid !important;
    gap: 12px !important;
}

.card {
    display: grid !important;
    grid-template-columns: 58px minmax(0, 1fr) 30px !important;
    align-items: center !important;
    gap: 12px !important;
    min-height: 88px !important;
    padding: 14px !important;
    border: 1px solid var(--learning-border) !important;
    border-radius: 19px !important;
    background: var(--learning-surface) !important;
    color: var(--learning-text) !important;
    text-decoration: none !important;
    box-shadow: var(--learning-shadow) !important;
    -webkit-tap-highlight-color: transparent;
}

.card:active {
    transform: scale(.985);
}

.card__icon,
.book-card__cover {
    width: 56px !important;
    height: 60px !important;
    display: grid !important;
    place-items: center !important;
    border-radius: 16px !important;
    background: var(--learning-soft) !important;
    color: var(--learning-primary) !important;
    font-family:
        "Segoe UI Emoji",
        "Apple Color Emoji",
        "Noto Color Emoji",
        sans-serif !important;
    font-size: 30px !important;
}

.card__body {
    min-width: 0 !important;
    display: block !important;
}

.card__title {
    display: block !important;
    color: var(--learning-primary-dark) !important;
    font-size: 17px !important;
    font-weight: 850 !important;
    line-height: 1.3 !important;
}

.card__text,
.book-card__meta {
    display: block !important;
    margin-top: 4px !important;
    overflow: hidden !important;
    color: var(--learning-muted) !important;
    font-size: 12.5px !important;
    line-height: 1.4 !important;
    white-space: nowrap !important;
    text-overflow: ellipsis !important;
}

.card__arrow {
    color: var(--learning-primary) !important;
    font-size: 28px !important;
    font-weight: 750 !important;
    text-align: center !important;
}

/* Bottom navigation */
.student-nav {
    position: fixed !important;
    z-index: 9999 !important;
    left: 50% !important;
    bottom: 0 !important;
    width: min(100%, var(--learning-width)) !important;
    min-height: var(--learning-nav-height) !important;
    display: grid !important;
    grid-template-columns: repeat(4, minmax(0, 1fr)) !important;
    padding:
        7px 8px
        calc(7px + env(safe-area-inset-bottom)) !important;
    border-top: 1px solid #dce5ed !important;
    background: rgba(255,255,255,.98) !important;
    box-shadow: 0 -6px 18px rgba(32, 65, 93, .11) !important;
    transform: translateX(-50%) !important;
    backdrop-filter: blur(14px);
}

.student-nav__item {
    position: relative !important;
    display: flex !important;
    min-width: 0 !important;
    flex-direction: column !important;
    align-items: center !important;
    justify-content: center !important;
    gap: 2px !important;
    color: #586879 !important;
    text-decoration: none !important;
}

.student-nav__icon {
    width: 42px !important;
    height: 34px !important;
    display: grid !important;
    place-items: center !important;
    border-radius: 12px !important;
    font-family:
        "Segoe UI Emoji",
        "Apple Color Emoji",
        "Noto Color Emoji",
        sans-serif !important;
    font-size: 23px !important;
}

.student-nav__label {
    overflow: hidden !important;
    max-width: 100% !important;
    color: inherit !important;
    font-size: 11.5px !important;
    font-weight: 750 !important;
    white-space: nowrap !important;
    text-overflow: ellipsis !important;
}

.student-nav__item.is-active {
    color: var(--learning-primary) !important;
}

.student-nav__item.is-active .student-nav__icon {
    background: var(--learning-soft) !important;
}

.student-nav__item.is-active::after {
    content: "";
    position: absolute;
    top: -7px;
    width: 52px;
    height: 3px;
    border-radius: 999px;
    background: var(--learning-primary);
}

@media (max-width: 390px) {
    .student-content {
        padding-left: 11px !important;
        padding-right: 11px !important;
    }

    .learning-intro {
        padding: 14px;
    }

    .card {
        grid-template-columns: 52px minmax(0, 1fr) 27px !important;
        gap: 10px !important;
        min-height: 80px !important;
        padding: 12px !important;
    }

    .card__icon,
    .book-card__cover {
        width: 50px !important;
        height: 56px !important;
        font-size: 27px !important;
    }

    .card__title {
        font-size: 16px !important;
    }
}

/* =========================================================
   EnglishSpeak Student UI — đồng bộ theo Home đã chốt
   Chỉ thay giao diện, không thay PHP / progress / unlock.
   ========================================================= */
:root{
    --learning-bg:#ffffff;
    --learning-surface:#ffffff;
    --learning-text:#0b4f9c;
    --learning-muted:#315d82;
    --learning-primary:#0b4f9c;
    --learning-primary-dark:#0b4f9c;
    --learning-soft:#eef7ff;
    --learning-border:#cfe4f5;
    --learning-shadow:0 7px 22px rgba(29,80,116,.07);
}

html,body{
    background:#ffffff!important;
    color:var(--learning-text)!important;
}
.student-app{
    background:#ffffff!important;
    box-shadow:0 0 24px rgba(20,60,90,.06)!important;
}

/* Bỏ dải xanh lớn trên đầu, trình bày header nhẹ như Home */
.student-header{
    position:relative!important;
    min-height:72px!important;
    padding:16px 14px 8px!important;
    background:#ffffff!important;
    color:var(--learning-primary)!important;
    box-shadow:none!important;
    border-bottom:0!important;
}
.student-back{
    width:42px!important;
    height:42px!important;
    background:#eef7ff!important;
    color:var(--learning-primary)!important;
    border:1px solid #d7e9f7!important;
    font-size:25px!important;
}
.student-header__text h1{
    color:var(--learning-primary)!important;
    font-size:22px!important;
    font-weight:900!important;
}
.student-header__text p{
    color:var(--learning-muted)!important;
    font-size:13.5px!important;
    font-weight:700!important;
}

.student-content{
    padding-top:10px!important;
}

/* Khối giới thiệu giống tinh thần pastel nhẹ của Home */
.learning-intro{
    padding:16px!important;
    border-color:var(--learning-border)!important;
    background:#eef7ff!important;
    box-shadow:none!important;
}
.learning-intro h2{
    color:var(--learning-primary)!important;
    font-size:20px!important;
    font-weight:900!important;
}
.learning-intro p{
    color:var(--learning-muted)!important;
    font-size:14px!important;
    font-weight:700!important;
}

/* Cards */
.card{
    border-color:#d4e3ee!important;
    background:#ffffff!important;
    color:var(--learning-primary)!important;
    box-shadow:0 5px 16px rgba(29,80,116,.06)!important;
}
.card__icon,.book-card__cover{
    background:#eef7ff!important;
    color:var(--learning-primary)!important;
}
.card__title{
    color:var(--learning-primary)!important;
    font-size:18px!important;
    font-weight:900!important;
}
.continue-card__lesson{
    color:var(--learning-primary)!important;
    font-size:14px!important;
    font-weight:850!important;
}
.card__text,.book-card__meta{
    color:var(--learning-muted)!important;
    font-size:13.5px!important;
    font-weight:700!important;
}
.continue-card__percent{
    color:var(--learning-primary)!important;
    font-size:13px!important;
    font-weight:900!important;
}
.card__arrow{
    color:var(--learning-primary)!important;
}
.continue-card__track{
    background:#dceaf5!important;
}
.continue-card__fill{
    background:#178bd2!important;
}

/* Menu chân đồng bộ Home */
.student-nav{
    background:#ffffff!important;
}
.student-nav__item{
    color:#315d82!important;
}
.student-nav__item.is-active{
    color:var(--learning-primary)!important;
}
.student-nav__item.is-active .student-nav__icon{
    background:#eef7ff!important;
}
.student-nav__item.is-active::after{
    background:var(--learning-primary)!important;
}
.student-nav__label{
    color:inherit!important;
    font-weight:850!important;
}


/* =========================================================
   Student Learning — final UI theo mẫu Home
   ========================================================= */

/* Ẩn header cũ hoàn toàn */
.student-header{
    display:none!important;
}

/* Phần từ Back/XP đến Sách của em được giữ cố định khi cuộn */
.learning-fixed-head{
    position:sticky;
    top:0;
    z-index:90;
    width:100%;
    padding-bottom:10px;
    background:#ffffff;
}

/* Hàng điều hướng trên */
.learning-topbar{
    width:100%;
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:12px;
    padding:12px 14px 8px;
}

.learning-back{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    width:42px;
    height:42px;
    color:#0b4f9c;
    text-decoration:none;
    font-size:32px;
    font-weight:900;
    line-height:1;
    -webkit-tap-highlight-color:transparent;
}
.learning-back:active{
    transform:scale(.96);
}

.learning-xp{
    display:inline-flex;
    align-items:center;
    gap:5px;
    min-height:38px;
    padding:6px 10px;
    border:1px solid #f1df9c;
    border-radius:14px;
    background:#fffdf4;
    color:#0b4f9c;
    font-size:15px;
    font-weight:900;
    line-height:1;
    white-space:nowrap;
}
.learning-xp__star{
    color:#e3a300;
    font-size:18px;
}

/* Khối Sách của em */
.learning-fixed-head .learning-intro{
    margin:0 14px!important;
    padding:14px 16px!important;
    border-color:#cfe4f5!important;
    background:#eef7ff!important;
    box-shadow:none!important;
}
.learning-fixed-head .learning-intro h2{
    margin:0!important;
    color:#0b4f9c!important;
    font-size:20px!important;
    font-weight:900!important;
    line-height:1.25!important;
}

/* Nội dung cuộn phía dưới */
.student-content{
    padding-top:0!important;
}
.card-list{
    padding-top:12px!important;
}

/* Phân cấp chữ trong card rõ hơn */
.card__title{
    color:#0b4f9c!important;
    font-size:18.5px!important;
    font-weight:900!important;
    line-height:1.25!important;
}
.continue-card__lesson{
    margin-top:6px!important;
    color:#315d82!important;
    font-size:14px!important;
    font-weight:800!important;
}
.continue-card__percent{
    color:#0b4f9c!important;
    font-size:13px!important;
    font-weight:900!important;
}

/* Hành động chính nổi rõ và có khoảng thở */
.continue-card .card__text{
    margin-top:10px!important;
    margin-bottom:2px!important;
    color:#0b4f9c!important;
    font-size:16px!important;
    font-weight:900!important;
}
.continue-card .card__text::before{
    content:"▶ ";
}

/* Sách đang học: nổi bật nhẹ, không thêm badge hay màu mạnh */
.continue-card.is-learning{
    border-color:#a9d4f3!important;
    background:#f8fcff!important;
    box-shadow:0 6px 18px rgba(29,80,116,.09)!important;
}
.continue-card.is-learning .book-card__cover{
    background:#e4f3ff!important;
}
.continue-card__lesson{
    font-size:14.5px!important;
    font-weight:850!important;
    line-height:1.35!important;
}

/* Menu chân giữ hệ màu Home */
.student-nav{
    background:#ffffff!important;
}
.student-nav__item{
    color:#315d82!important;
}
.student-nav__item.is-active{
    color:#0b4f9c!important;
}
.student-nav__item.is-active .student-nav__icon{
    background:#eef7ff!important;
}
.student-nav__item.is-active::after{
    background:#0b4f9c!important;
}
.student-nav__label{
    color:inherit!important;
    font-size:12.5px!important;
    font-weight:850!important;
}

</style>

<div class="learning-fixed-head">
    <div class="learning-topbar">
        <a class="learning-back" href="student-home.php" aria-label="Quay về Trang chủ">←</a>

        <div class="learning-xp" aria-label="Tổng XP">
            <span class="learning-xp__star" aria-hidden="true">★</span>
            <span><?= $totalXp ?> XP</span>
        </div>
    </div>

    <section class="learning-intro">
        <h2>📚 My books</h2>
    </section>
</div>

<div class="card-list">
    <?php if ($learningPaths === []): ?>
        <div class="card" style="grid-template-columns:58px minmax(0,1fr);">
            <span class="card__icon" aria-hidden="true">📖</span>
            <span class="card__body">
                <span class="card__title">Chưa có sách đang học</span>
                <span class="card__text">Vào Trang chủ để chọn bộ sách và lớp.</span>
            </span>
        </div>
    <?php else: ?>
        <?php foreach ($learningPaths as $path): ?>
            <?php
            $currentLesson = $path['current_lesson'];
            $progress = (int)($path['progress'] ?? 0);
            $buttonLabel = $progress >= 100 ? 'Ôn lại' : 'Vào học';
            ?>
            <a
                class="card continue-card<?= $progress > 0 ? ' is-learning' : '' ?>"
                href="<?= htmlspecialchars(
                    (string)$path['continue_url'],
                    ENT_QUOTES,
                    'UTF-8'
                ) ?>"
            >
                <span class="book-card__cover" aria-hidden="true">📘</span>

                <span class="card__body">
                    <span class="card__title">
                        <?= htmlspecialchars(
                            (string)$path['book_name']
                            . ' • '
                            . (string)$path['level_name'],
                            ENT_QUOTES,
                            'UTF-8'
                        ) ?>
                    </span>

                    <?php if ($currentLesson): ?>
                        <span class="continue-card__lesson">
                            <?= htmlspecialchars(
                                (string)$currentLesson['unit_number']
                                . ' • '
                                . (string)$currentLesson['lesson_title_text'],
                                ENT_QUOTES,
                                'UTF-8'
                            ) ?>
                        </span>

                        <span class="continue-card__progress">
                            <span
                                class="continue-card__track"
                                aria-hidden="true"
                            >
                                <span
                                    class="continue-card__fill"
                                    style="width:<?= $progress ?>%"
                                ></span>
                            </span>

                            <span class="continue-card__percent">
                                <?= $progress ?>%
                            </span>
                        </span>

                        <span class="card__text">
                            <?= htmlspecialchars(
                                $buttonLabel,
                                ENT_QUOTES,
                                'UTF-8'
                            ) ?>
                        </span>
                    <?php endif; ?>
                </span>

                <span class="card__arrow" aria-hidden="true">›</span>
            </a>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

<?php include __DIR__ . '/../includes/student-layout-end.php'; ?>
