<?php
declare(strict_types=1);

session_start();

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

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/lesson_progress_engine.php';
$pdo = getDbConnection();

$bookSlug = trim((string)($_GET['book'] ?? ''));
$levelSlug = trim((string)($_GET['level'] ?? ''));
$levelId = max(0, (int)($_GET['level_id'] ?? 0));
$unitId = max(0, (int)($_GET['unit_id'] ?? ($_GET['id'] ?? 0)));

if ($bookSlug === '' || $levelId <= 0 || $unitId <= 0) {
    header('Location: student-learning.php');
    exit;
}

$contextStmt = $pdo->prepare(
    "SELECT
        u.id AS unit_id,
        u.unit_number,
        u.title AS unit_title,
        u.level_id,
        l.id AS level_id,
        l.name AS level_name,
        l.slug AS level_slug,
        b.id AS book_id,
        b.name AS book_name,
        b.slug AS book_slug
     FROM units u
     INNER JOIN levels l
        ON l.id = u.level_id
     INNER JOIN books b
        ON b.id = l.book_id
     WHERE u.id = ?
       AND l.id = ?
       AND b.slug = ?
       AND u.status = 'active'
       AND l.status = 'active'
       AND b.status = 'active'
     LIMIT 1"
);
$contextStmt->execute([$unitId, $levelId, $bookSlug]);
$context = $contextStmt->fetch(PDO::FETCH_ASSOC);

if (!$context) {
    http_response_code(404);
    exit('Không tìm thấy Unit trong cấp độ đã chọn.');
}

/*
 * UNIT GATE
 * Unit đầu tiên luôn mở.
 * Unit sau KHÔNG mở ngay khi Unit trước vừa completed.
 * Nó chỉ mở khi Lesson đầu tiên của Unit hiện tại thực sự đến lượt mở:
 * - sequential_daily: Unit trước hoàn thành và đã sang ngày hôm sau.
 * - scheduled_date: Unit trước hoàn thành và đã đến unlock_date.
 * Chặn cả trường hợp gõ URL trực tiếp.
 */
$unitOrderStmt = $pdo->prepare(
    "SELECT id
     FROM units
     WHERE level_id = ?
       AND status = 'active'
     ORDER BY sort_order ASC, id ASC"
);
$unitOrderStmt->execute([(int)$context['level_id']]);
$orderedUnitIds = array_map('intval', $unitOrderStmt->fetchAll(PDO::FETCH_COLUMN));

$currentUnitIndex = array_search($unitId, $orderedUnitIds, true);
$unitUnlocked = ($currentUnitIndex === 0);
$todayForUnitGate = new DateTimeImmutable('today');

if ($currentUnitIndex !== false && $currentUnitIndex > 0) {
    $previousUnitId = $orderedUnitIds[$currentUnitIndex - 1];

    $previousLastLessonStmt = $pdo->prepare(
        "SELECT l.id, scp.status, scp.completed_at
         FROM lessons l
         LEFT JOIN student_content_progress scp
           ON scp.student_id = ?
          AND scp.content_type = 'lesson'
          AND scp.content_id = l.id
         WHERE l.unit_id = ?
           AND l.status = 'active'
         ORDER BY l.sort_order DESC, l.id DESC
         LIMIT 1"
    );
    $previousLastLessonStmt->execute([
        (int)$_SESSION['student_id'],
        $previousUnitId
    ]);
    $previousLastLesson = $previousLastLessonStmt->fetch(PDO::FETCH_ASSOC) ?: [];

    $firstLessonStmt = $pdo->prepare(
        "SELECT unlock_mode, unlock_date
         FROM lessons
         WHERE unit_id = ?
           AND status = 'active'
         ORDER BY sort_order ASC, id ASC
         LIMIT 1"
    );
    $firstLessonStmt->execute([$unitId]);
    $firstLessonGate = $firstLessonStmt->fetch(PDO::FETCH_ASSOC) ?: [];

    $previousCompleted =
        (string)($previousLastLesson['status'] ?? '') === 'completed';
    $previousCompletedAt =
        trim((string)($previousLastLesson['completed_at'] ?? ''));

    $unitUnlocked = false;

    if ($previousCompleted && $previousCompletedAt !== '' && $firstLessonGate !== []) {
        $firstMode = strtolower(trim(
            (string)($firstLessonGate['unlock_mode'] ?? 'sequential_daily')
        ));
        $firstUnlockDate = trim((string)($firstLessonGate['unlock_date'] ?? ''));

        if ($firstMode === 'scheduled_date') {
            if ($firstUnlockDate !== '') {
                try {
                    $scheduledDate = (new DateTimeImmutable($firstUnlockDate))->setTime(0, 0);
                    $unitUnlocked = $todayForUnitGate >= $scheduledDate;
                } catch (Throwable $e) {
                    $unitUnlocked = false;
                }
            }
        } else {
            try {
                $completedDate =
                    (new DateTimeImmutable($previousCompletedAt))->setTime(0, 0);
                $unitUnlocked = $todayForUnitGate > $completedDate;
            } catch (Throwable $e) {
                $unitUnlocked = false;
            }
        }
    }
}

if ($currentUnitIndex === false || !$unitUnlocked) {
    http_response_code(403);
    exit('Unit này chưa đến ngày mở.');
}

$lessonStmt = $pdo->prepare(
    "SELECT
        id,
        unit_id,
        lesson_number,
        title,
        description,
        unlock_mode,
        unlock_date,
        sort_order,
        status
     FROM lessons
     WHERE unit_id = ?
       AND status = 'active'
     ORDER BY sort_order ASC, id ASC"
);
$lessonStmt->execute([$unitId]);
$lessons = $lessonStmt->fetchAll(PDO::FETCH_ASSOC);

/*
 * TEACHER + CLASS + ACADEMIC YEAR LESSON SCHEDULE OVERLAY
 *
 * Lấy đúng scope hiện tại của học sinh:
 * school + academic year + grade + class.
 *
 * Sau đó đọc trực tiếp teacher_lesson_schedules theo đúng scope đó.
 * Không cần suy ngược teacher qua teacher_class_assignments nữa, vì chính
 * teacher_lesson_schedules đã lưu teacher_id và scope lớp tại thời điểm GV đặt lịch.
 *
 * IMPORTANT:
 * - Chỉ overlay unlock_mode / unlock_date.
 * - Không ghi XP/progress.
 * - Không sửa dữ liệu gốc trong lessons.
 * - Nếu lớp không có schedule riêng, giữ nguyên rule của lessons.
 */
if ($lessons !== []) {
    try {
        $studentIdForSchedule = (int)$_SESSION['student_id'];
        $studentScheduleContext = null;

        /*
         * Scope mở Lesson phải theo NĂM HỌC HIỆN TẠI của hệ thống,
         * không lấy academic_year_id/grade/class_name tương lai trong students.
         *
         * Ví dụ:
         * - academic_years.is_current = 1 => 2026-2027
         * - HS có lịch sử 2026-2027: lớp 4/1
         * - HS đã được chuẩn bị 2027-2028: lớp 5/1
         * => khi 2026-2027 còn current, schedule phải dùng lớp 4/1.
         */
        $currentAcademicYearStmt = $pdo->query(
            "SELECT id
             FROM academic_years
             WHERE is_current = 1
             ORDER BY id DESC
             LIMIT 1"
        );
        $currentAcademicYearId = (int)($currentAcademicYearStmt->fetchColumn() ?: 0);

        if ($currentAcademicYearId > 0) {
            // Nguồn chuẩn: lịch sử lớp của HS đúng năm học hiện tại.
            $historyStmt = $pdo->prepare(
                "SELECT academic_year_id, grade, class_name, school_id
                 FROM student_class_history
                 WHERE student_id = ?
                   AND academic_year_id = ?
                 ORDER BY recorded_at DESC, id DESC
                 LIMIT 1"
            );
            $historyStmt->execute([
                $studentIdForSchedule,
                $currentAcademicYearId,
            ]);
            $studentScheduleContext =
                $historyStmt->fetch(PDO::FETCH_ASSOC) ?: null;

            /*
             * Fallback an toàn cho dữ liệu cũ:
             * chỉ dùng students nếu chính row students cũng thuộc
             * đúng academic_year_id hiện tại.
             */
            if (!$studentScheduleContext) {
                $studentContextStmt = $pdo->prepare(
                    "SELECT academic_year_id, grade, class_name, school_id
                     FROM students
                     WHERE id = ?
                       AND academic_year_id = ?
                     LIMIT 1"
                );
                $studentContextStmt->execute([
                    $studentIdForSchedule,
                    $currentAcademicYearId,
                ]);
                $studentScheduleContext =
                    $studentContextStmt->fetch(PDO::FETCH_ASSOC) ?: null;
            }
        }

        if (
            $studentScheduleContext
            && (int)($studentScheduleContext['academic_year_id'] ?? 0) > 0
            && (int)($studentScheduleContext['school_id'] ?? 0) > 0
            && (int)($studentScheduleContext['grade'] ?? 0) > 0
            && trim((string)($studentScheduleContext['class_name'] ?? '')) !== ''
        ) {
            $academicYearIdForSchedule =
                (int)$studentScheduleContext['academic_year_id'];
            $schoolIdForSchedule =
                (int)$studentScheduleContext['school_id'];
            $gradeForSchedule =
                (int)$studentScheduleContext['grade'];
            $classNameForSchedule =
                trim((string)$studentScheduleContext['class_name']);

            $scheduleLessonIds = array_map(
                static fn(array $lesson): int => (int)$lesson['id'],
                $lessons
            );

            if ($scheduleLessonIds !== []) {
                $schedulePlaceholders = implode(
                    ',',
                    array_fill(0, count($scheduleLessonIds), '?')
                );

                /*
                 * Chọn schedule mới nhất nếu vì dữ liệu cũ có hơn một row cùng scope.
                 * Có grade trong điều kiện để tuyệt đối không ăn lịch của khối khác.
                 */
                $scheduleStmt = $pdo->prepare(
                    "SELECT lesson_id, unlock_mode, unlock_date
                     FROM teacher_lesson_schedules
                     WHERE school_id = ?
                       AND academic_year_id = ?
                       AND grade = ?
                       AND class_name = ?
                       AND lesson_id IN ({$schedulePlaceholders})
                     ORDER BY id ASC"
                );

                $scheduleStmt->execute(array_merge(
                    [
                        $schoolIdForSchedule,
                        $academicYearIdForSchedule,
                        $gradeForSchedule,
                        $classNameForSchedule,
                    ],
                    $scheduleLessonIds
                ));

                $classSchedules = [];
                foreach ($scheduleStmt->fetchAll(PDO::FETCH_ASSOC) as $scheduleRow) {
                    // ORDER BY id ASC -> row mới hơn sẽ ghi đè row cũ.
                    $classSchedules[(int)$scheduleRow['lesson_id']] = $scheduleRow;
                }

                foreach ($lessons as &$lessonForSchedule) {
                    $lessonIdForSchedule = (int)$lessonForSchedule['id'];

                    if (!isset($classSchedules[$lessonIdForSchedule])) {
                        continue;
                    }

                    $lessonForSchedule['unlock_mode'] =
                        (string)$classSchedules[$lessonIdForSchedule]['unlock_mode'];
                    $lessonForSchedule['unlock_date'] =
                        $classSchedules[$lessonIdForSchedule]['unlock_date'];
                }
                unset($lessonForSchedule);
            }
        }
    } catch (Throwable $e) {
        error_log(
            '[EnglishSpeak student lesson class schedule] ' .
            $e->getMessage()
        );
    }
}

$lessonStates = englishSpeakGetUnitLessonStates(
    $pdo,
    (int)$_SESSION['student_id'],
    $unitId
);

/*
 * LESSON UNLOCK OVERLAY
 * Giữ nguyên progress/XP hiện tại, chỉ thay quyền mở Lesson.
 *
 * - sequential_daily:
 *   Lesson đầu mở ngay.
 *   Lesson kế tiếp chỉ mở khi Lesson trước đã completed
 *   VÀ sang ngày sau ngày hoàn thành Lesson trước.
 *
 * - scheduled_date:
 *   Mở khi hôm nay >= unlock_date.
 *
 * Lesson đã từng bắt đầu/hoàn thành luôn được giữ mở để học lại.
 */
$studentId = (int)$_SESSION['student_id'];
$today = new DateTimeImmutable('today');

$lessonCompletionDates = [];
if ($lessons !== []) {
    $unlockLessonIds = array_map(
        static fn(array $lesson): int => (int)$lesson['id'],
        $lessons
    );
    $unlockPlaceholders = implode(',', array_fill(0, count($unlockLessonIds), '?'));

    $completionStmt = $pdo->prepare(
        "SELECT content_id, completed_at
         FROM student_content_progress
         WHERE student_id = ?
           AND content_type = 'lesson'
           AND content_id IN ({$unlockPlaceholders})
           AND status = 'completed'"
    );
    $completionStmt->execute(array_merge([$studentId], $unlockLessonIds));

    foreach ($completionStmt->fetchAll(PDO::FETCH_ASSOC) as $completionRow) {
        $lessonCompletionDates[(int)$completionRow['content_id']] =
            (string)($completionRow['completed_at'] ?? '');
    }
}

foreach ($lessons as $lessonIndex => $lesson) {
    $lessonIdForUnlock = (int)$lesson['id'];
    $existingState = $lessonStates[$lessonIdForUnlock] ?? [
        'unlocked' => false,
        'status' => 'not_started',
        'progress_percent' => 0,
    ];

    $existingStatus = (string)($existingState['status'] ?? 'not_started');

    // Một Lesson đã học rồi không được khóa lại.
    if (in_array($existingStatus, ['in_progress', 'completed'], true)) {
        $lessonStates[$lessonIdForUnlock]['unlocked'] = true;
        continue;
    }

    $unlockMode = strtolower(trim((string)($lesson['unlock_mode'] ?? 'sequential_daily')));
    $unlockDateRaw = trim((string)($lesson['unlock_date'] ?? ''));

    if ($unlockMode === 'scheduled_date') {
        $scheduledUnlocked = false;

        if ($unlockDateRaw !== '') {
            try {
                $unlockDate = new DateTimeImmutable($unlockDateRaw);
                $scheduledUnlocked = $today >= $unlockDate->setTime(0, 0);
            } catch (Throwable $e) {
                $scheduledUnlocked = false;
            }
        }

        if ($lessonIndex === 0) {
            // Lesson đầu Unit: điều kiện Unit trước đã được UNIT GATE kiểm tra.
            $lessonStates[$lessonIdForUnlock]['unlocked'] = $scheduledUnlocked;
        } else {
            $previousLesson = $lessons[$lessonIndex - 1];
            $previousLessonId = (int)$previousLesson['id'];
            $previousState = $lessonStates[$previousLessonId] ?? [];
            $previousCompleted =
                (string)($previousState['status'] ?? '') === 'completed';

            $lessonStates[$lessonIdForUnlock]['unlocked'] =
                $previousCompleted && $scheduledUnlocked;
        }
        continue;
    }

    // Mặc định: mỗi ngày mở tối đa 1 Lesson.
    // Lesson đầu Unit 1 mở ngay. Lesson đầu các Unit sau đã được UNIT GATE
    // kiểm tra theo ngày hoàn thành Lesson cuối của Unit trước.
    if ($lessonIndex === 0) {
        $lessonStates[$lessonIdForUnlock]['unlocked'] = true;
        continue;
    }

    $previousLesson = $lessons[$lessonIndex - 1];
    $previousLessonId = (int)$previousLesson['id'];
    $previousState = $lessonStates[$previousLessonId] ?? [];
    $previousCompleted =
        (string)($previousState['status'] ?? '') === 'completed';

    $previousCompletedAt =
        trim((string)($lessonCompletionDates[$previousLessonId] ?? ''));

    $dayHasAdvanced = false;
    if ($previousCompleted && $previousCompletedAt !== '') {
        try {
            $previousCompletedDate = new DateTimeImmutable($previousCompletedAt);
            $dayHasAdvanced =
                $today > $previousCompletedDate->setTime(0, 0);
        } catch (Throwable $e) {
            $dayHasAdvanced = false;
        }
    }

    $lessonStates[$lessonIdForUnlock]['unlocked'] =
        $previousCompleted && $dayHasAdvanced;
}


$lessonIds = array_map(
    static fn(array $lesson): int => (int)$lesson['id'],
    $lessons
);

$activitiesByLesson = [];
$activityProgressById = [];

if ($lessonIds !== []) {
    $lessonPlaceholders = implode(
        ',',
        array_fill(0, count($lessonIds), '?')
    );

    $activityStmt = $pdo->prepare(
        "SELECT
            id,
            lesson_id,
            title,
            activity_type,
            xp_reward,
            sort_order
         FROM activities
         WHERE lesson_id IN ({$lessonPlaceholders})
           AND status = 'active'
         ORDER BY lesson_id ASC, sort_order ASC, id ASC"
    );
    $activityStmt->execute($lessonIds);
    $lessonActivities = $activityStmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($lessonActivities as $activity) {
        $activitiesByLesson[(int)$activity['lesson_id']][] = $activity;
    }

    $activityIds = array_map(
        static fn(array $activity): int => (int)$activity['id'],
        $lessonActivities
    );

    if ($activityIds !== []) {
        $activityPlaceholders = implode(
            ',',
            array_fill(0, count($activityIds), '?')
        );

        $activityProgressStmt = $pdo->prepare(
            "SELECT
                content_id,
                status,
                best_score,
                xp_earned
             FROM student_content_progress
             WHERE student_id = ?
               AND content_type = 'activity'
               AND content_id IN ({$activityPlaceholders})"
        );
        $activityProgressStmt->execute(
            array_merge(
                [(int)$_SESSION['student_id']],
                $activityIds
            )
        );

        foreach (
            $activityProgressStmt->fetchAll(PDO::FETCH_ASSOC)
            as $activityProgress
        ) {
            $activityProgressById[(int)$activityProgress['content_id']] =
                $activityProgress;
        }
    }
}


$lessonPracticeStats = [];

if ($lessonIds !== []) {
    $practiceStatsStmt = $pdo->prepare(
        "SELECT
            a.lesson_id,
            COUNT(*) AS practice_count,
            COALESCE(SUM(e.xp_change), 0) AS practice_xp
         FROM xp_transactions e
         INNER JOIN activities a
            ON a.id = e.activity_id
         WHERE e.student_id = ?
           AND a.lesson_id IN ({$lessonPlaceholders})
           AND e.xp_source IN ('practice', 'new_best')
         GROUP BY a.lesson_id"
    );

    $practiceStatsStmt->execute(
        array_merge(
            [(int)$_SESSION['student_id']],
            $lessonIds
        )
    );

    foreach (
        $practiceStatsStmt->fetchAll(PDO::FETCH_ASSOC)
        as $practiceRow
    ) {
        $lessonPracticeStats[(int)$practiceRow['lesson_id']] = [
            'count' => max(
                0,
                (int)($practiceRow['practice_count'] ?? 0)
            ),
            'xp' => max(
                0,
                (int)($practiceRow['practice_xp'] ?? 0)
            ),
        ];
    }
}

function studentLessonActivityLabel(array $activity): string
{
    $title = trim((string)($activity['title'] ?? ''));

    if ($title !== '') {
        return $title;
    }

    $type = strtolower(trim((string)($activity['activity_type'] ?? '')));

    return match ($type) {
        'flashcard', 'flashcards' => 'Flashcards',
        'listen_repeat', 'listen_and_repeat' => 'Listen & Repeat',
        'speaking', 'sentence_speaking',
        'speaking_sentences', 'sentence_listen_repeat' => 'Speaking',
        'memory' => 'Memory',
        'matching' => 'Matching',
        'quiz' => 'Quiz',
        'word_builder' => 'Word Builder',
        'word_unscramble', 'unscramble' => 'Unscramble',
        default => 'Hoạt động',
    };
}

function studentLessonActivityIcon(array $activity): string
{
    $type = strtolower(trim((string)($activity['activity_type'] ?? '')));

    return match ($type) {
        'flashcard', 'flashcards' => '🗂️',
        'listen_repeat', 'listen_and_repeat' => '🎧',
        'speaking', 'sentence_speaking',
        'speaking_sentences', 'sentence_listen_repeat' => '🎤',
        'memory' => '🧠',
        'matching' => '🧩',
        'quiz' => '📝',
        'word_builder' => '🔤',
        'word_unscramble', 'unscramble' => '🔀',
        default => '🎯',
    };
}

$totalLessons = count($lessons);
$completedLessons = 0;

foreach ($lessons as $lesson) {
    $state = $lessonStates[(int)$lesson['id']] ?? [];
    if (($state['status'] ?? '') === 'completed') {
        $completedLessons++;
    }
}

$unitProgressPercent = $totalLessons > 0
    ? (int)round(($completedLessons / $totalLessons) * 100)
    : 0;

$continueUrl = '';
$continueLabel = 'Vào học';
$reviewPreviousUrl = '';

foreach ($lessons as $lesson) {
    $lessonIdForContinue = (int)$lesson['id'];
    $state = $lessonStates[$lessonIdForContinue] ?? [
        'unlocked' => false,
        'status' => 'not_started',
    ];

    if (
        (bool)($state['unlocked'] ?? false)
        && (string)($state['status'] ?? '') !== 'completed'
    ) {
        $rawNumber = trim((string)$lesson['lesson_number']);
        $numberForUrl = preg_match('/(\d+)/', $rawNumber, $match)
            ? (int)$match[1]
            : $rawNumber;

        $continueUrl = 'student-activities.php?' . http_build_query([
            'book' => (string)$context['book_slug'],
            'level' => (string)$context['level_slug'],
            'level_id' => (int)$context['level_id'],
            'unit_id' => (int)$context['unit_id'],
            'lesson_id' => $lessonIdForContinue,
            'lesson' => $numberForUrl,
        ]);
        break;
    }
}

if ($continueUrl === '' && $lessons !== []) {
    /*
     * Chỉ hiện "Ôn lại" nếu thực sự có một Lesson đã mở và đã học.
     * Không được mặc định trỏ về Lesson 1 khi tất cả Lesson đang bị khóa
     * bởi unlock_date / sequential_daily.
     */
    foreach (array_reverse($lessons) as $reviewLesson) {
        $reviewLessonId = (int)$reviewLesson['id'];
        $reviewState = $lessonStates[$reviewLessonId] ?? [
            'unlocked' => false,
            'status' => 'not_started',
        ];

        $reviewStatus = (string)($reviewState['status'] ?? 'not_started');

        if (
            (bool)($reviewState['unlocked'] ?? false)
            && in_array($reviewStatus, ['in_progress', 'completed'], true)
        ) {
            $rawNumber = trim((string)$reviewLesson['lesson_number']);
            $numberForUrl = preg_match('/(\d+)/', $rawNumber, $match)
                ? (int)$match[1]
                : $rawNumber;

            $continueUrl = 'student-activities.php?' . http_build_query([
                'book' => (string)$context['book_slug'],
                'level' => (string)$context['level_slug'],
                'level_id' => (int)$context['level_id'],
                'unit_id' => (int)$context['unit_id'],
                'lesson_id' => $reviewLessonId,
                'lesson' => $numberForUrl,
            ]);
            $continueLabel = 'Ôn lại';
            break;
        }
    }
}

if ($continueLabel === 'Ôn lại' && $continueUrl !== '') {
    $reviewPreviousUrl = $continueUrl;
}


$_SESSION['last_learning_url'] = (string)($_SERVER['REQUEST_URI'] ?? '');

$pageTitle = (string)$context['unit_number'];
$pageSubtitle = (string)$context['unit_title'];
$showBack = true;
$backUrl = 'student-units.php?' . http_build_query([
    'book' => (string)$context['book_slug'],
    'level' => (string)$context['level_slug'],
    'level_id' => (int)$context['level_id'],
]);
$activeStudentNav = 'learning';

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

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

* {
    box-sizing: border-box;
}

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

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

.student-app {
    width: min(100%, var(--ls-width)) !important;
    min-height: 100vh !important;
    margin: 0 auto !important;
    background: #f7fbff !important;
    box-shadow: 0 0 28px rgba(27, 73, 108, .08) !important;
}

.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: #fff !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: #fff !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: #fff !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;
}

.context-card {
    display: grid;
    grid-template-columns: 58px minmax(0, 1fr);
    align-items: center;
    gap: 12px;
    margin-bottom: 14px;
    padding: 15px;
    border-radius: 20px;
    background: linear-gradient(135deg, #edf6ff, #e6f1ff);
    box-shadow: var(--ls-shadow);
}

.context-card__icon {
    width: 54px;
    height: 58px;
    display: grid;
    place-items: center;
    border-radius: 15px;
    background: #fff;
    font-size: 31px;
}

.context-card strong {
    display: block;
    color: var(--ls-primary-dark);
    font-size: 17px;
}

.context-card span {
    display: block;
    margin-top: 4px;
    color: var(--ls-muted);
    font-size: 13px;
}


.unit-progress {
    margin-bottom: 14px;
    padding: 15px;
    border: 1px solid var(--ls-border);
    border-radius: 20px;
    background: #fff;
    box-shadow: var(--ls-shadow);
}

.unit-progress__top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
}

.unit-progress__top strong {
    color: var(--ls-text);
    font-size: 15px;
}

.unit-progress__top span {
    color: var(--ls-primary-dark);
    font-size: 13px;
    font-weight: 850;
}

.unit-progress__track {
    height: 10px;
    margin-top: 11px;
    overflow: hidden;
    border-radius: 999px;
    background: #dceaf5;
}

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

.unit-progress__caption {
    margin-top: 8px;
    color: var(--ls-muted);
    font-size: 12px;
}

.continue-button {
    width: 100%;
    min-height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 13px;
    border-radius: 15px;
    background: linear-gradient(135deg, #2685df, #18a7dd);
    color: #fff;
    font-size: 15px;
    font-weight: 850;
    text-decoration: none;
}

.lesson-unlock-notice {
    margin-bottom: 14px;
    padding: 14px 15px;
    border: 1px solid #f1df9c;
    border-radius: 18px;
    background: #fffdf4;
    color: #315d82;
    font-size: 13px;
    line-height: 1.5;
}

.lesson-unlock-notice strong {
    display: block;
    margin-bottom: 4px;
    color: #0b4f9c;
    font-size: 14px;
}

.lesson-unlock-notice a {
    color: #0b67ac;
    font-weight: 850;
    text-decoration: none;
}

.lesson-list {
    display: grid;
    gap: 11px;
}

.lesson-card {
    display: grid;
    grid-template-columns: 52px minmax(0, 1fr) 32px;
    align-items: start;
    gap: 12px;
    min-height: 82px;
    padding: 13px;
    border: 1px solid var(--ls-border);
    border-radius: 18px;
    background: var(--ls-surface);
    color: var(--ls-text);
    text-decoration: none;
    box-shadow: var(--ls-shadow);
    -webkit-tap-highlight-color: transparent;
}

.lesson-card--locked {
    cursor: not-allowed;
    opacity: .62;
    filter: grayscale(.15);
}

.lesson-card__locked-note {
    grid-column: 2 / 4;
    margin-top: 2px;
    color: #8a6a10;
    font-size: 12px;
    font-weight: 800;
    line-height: 1.4;
}

.lesson-card__locked-note.is-scheduled {
    color: #8a5b00;
}

.lesson-card__meta {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-top: 7px;
}

.lesson-card__progress {
    min-width: 48px;
    color: var(--ls-primary-dark);
    font-size: 12px;
    font-weight: 850;
}

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

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

.lesson-card__status {
    min-width: 66px;
    color: var(--ls-muted);
    font-size: 11px;
    font-weight: 800;
    text-align: right;
}

.lesson-card--locked .lesson-card__arrow {
    font-size: 19px;
}


.lesson-card__summary {
    grid-column: 2 / 4;
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 7px;
    margin-top: 4px;
}

.lesson-card__activity {
    display: flex;
    min-width: 0;
    align-items: center;
    gap: 6px;
    padding: 7px 8px;
    border-radius: 10px;
    background: #f3f8fc;
    color: var(--ls-muted);
    font-size: 11.5px;
    font-weight: 750;
}

.lesson-card__activity.is-completed {
    background: #eefaf2;
    color: #18864b;
}

.lesson-card__activity-icon {
    flex: 0 0 auto;
}

.lesson-card__activity-name {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

.lesson-card__stats {
    grid-column: 2 / 4;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
    margin-top: 3px;
    padding-top: 9px;
    border-top: 1px solid #edf2f6;
    color: var(--ls-muted);
    font-size: 11.5px;
    font-weight: 750;
}

.lesson-card__xp-summary {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 3px;
    color: var(--ls-muted);
    text-align: right;
}

.lesson-card__xp-summary span:first-child {
    color: var(--ls-primary-dark);
    font-weight: 850;
}

.lesson-card__xp-summary span:last-child {
    color: #18864b;
}

.lesson-card--locked .lesson-card__summary,
.lesson-card--locked .lesson-card__stats {
    display: none;
}

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

.lesson-card__number {
    width: 52px;
    height: 52px;
    display: grid;
    place-items: center;
    border-radius: 16px;
    background: var(--ls-soft);
    color: var(--ls-primary);
    font-size: 20px;
    font-weight: 850;
}

.lesson-card__copy {
    min-width: 0;
}

.lesson-card__copy strong {
    display: block;
    margin: 0;
    color: var(--ls-primary-dark);
    font-size: 16px;
    font-weight: 850;
    line-height: 1.3;
}

.lesson-card__copy span {
    display: block;
    margin-top: 5px;
    overflow: hidden;
    color: var(--ls-muted);
    font-size: 12.5px;
    line-height: 1.4;
    white-space: nowrap;
    text-overflow: ellipsis;
}

.lesson-card__arrow {
    color: var(--ls-primary);
    font-size: 27px;
    font-weight: 700;
    text-align: center;
}

.lesson-empty {
    padding: 25px 18px;
    border: 1px dashed #bdd7e8;
    border-radius: 18px;
    background: rgba(255,255,255,.75);
    color: var(--ls-muted);
    text-align: center;
    line-height: 1.5;
}

.student-nav {
    position: fixed !important;
    z-index: 9999 !important;
    left: 50% !important;
    bottom: 0 !important;
    width: min(100%, var(--ls-width)) !important;
    min-height: var(--ls-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-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(--ls-primary) !important;
}

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

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

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

    .lesson-card {
        grid-template-columns: 48px minmax(0, 1fr) 28px;
        gap: 10px;
        min-height: 76px;
        padding: 11px;
    }

    .lesson-card__summary {
        grid-template-columns: 1fr;
    }

    .lesson-card__stats {
        align-items: flex-start;
        flex-direction: column;
        gap: 6px;
    }

    .lesson-card__xp-summary {
        align-items: flex-start;
        text-align: left;
    }

    .lesson-card__number {
        width: 48px;
        height: 48px;
        font-size: 18px;
    }
}
</style>

<section class="context-card">
    <div class="context-card__icon" aria-hidden="true">📘</div>
    <div>
        <strong><?= htmlspecialchars((string)$context['level_name'], ENT_QUOTES, 'UTF-8') ?></strong>
        <span><?= htmlspecialchars((string)$context['book_name'], ENT_QUOTES, 'UTF-8') ?></span>
    </div>
</section>

<section class="unit-progress" aria-label="Tiến độ bài học">
    <div class="unit-progress__top">
        <strong>Tiến độ bài học</strong>
        <span><?= $unitProgressPercent ?>%</span>
    </div>

    <div class="unit-progress__track" aria-hidden="true">
        <div
            class="unit-progress__fill"
            style="width:<?= $unitProgressPercent ?>%"
        ></div>
    </div>

    <div class="unit-progress__caption">
        <?= $completedLessons ?> / <?= $totalLessons ?> Lesson đã hoàn thành
    </div>

    <?php if ($continueUrl !== ''): ?>
        <a
            class="continue-button"
            href="<?= htmlspecialchars($continueUrl, ENT_QUOTES, 'UTF-8') ?>"
        >
            <?= htmlspecialchars($continueLabel, ENT_QUOTES, 'UTF-8') ?> →
        </a>
    <?php endif; ?>
</section>


<section class="lesson-list" aria-label="Danh sách bài học">
    <?php if ($lessons === []): ?>
        <div class="lesson-empty">
            Unit này chưa có bài học.
        </div>
    <?php endif; ?>

    <?php foreach ($lessons as $lesson): ?>
        <?php
        $rawLessonNumber = trim((string)$lesson['lesson_number']);
        $lessonNumberForUrl = preg_match('/(\d+)/', $rawLessonNumber, $lessonMatch)
            ? (int)$lessonMatch[1]
            : $rawLessonNumber;

        $query = http_build_query([
            'book' => (string)$context['book_slug'],
            'level' => (string)$context['level_slug'],
            'level_id' => (int)$context['level_id'],
            'unit_id' => (int)$context['unit_id'],
            'lesson_id' => (int)$lesson['id'],
            'lesson' => $lessonNumberForUrl,
        ]);
        ?>
        <?php
        $lessonState = $lessonStates[(int)$lesson['id']] ?? [
            'unlocked' => false,
            'status' => 'not_started',
            'progress_percent' => 0,
        ];
        $isUnlocked = (bool)$lessonState['unlocked'];
        $lessonProgressPercent = (int)$lessonState['progress_percent'];

        $currentLessonActivities =
            $activitiesByLesson[(int)$lesson['id']] ?? [];

        $completedActivityCount = 0;
        $earnedCompletionXp = 0;
        $possibleCompletionXp = 0;

        $practiceStats = $lessonPracticeStats[(int)$lesson['id']] ?? [
            'count' => 0,
            'xp' => 0,
        ];
        $practiceCount = (int)$practiceStats['count'];
        $practiceXp = (int)$practiceStats['xp'];

        foreach ($currentLessonActivities as $currentActivity) {
            $currentProgress =
                $activityProgressById[(int)$currentActivity['id']] ?? [];

            $isActivityCompleted =
                strtolower(trim((string)($currentProgress['status'] ?? '')))
                === 'completed';

            if ($isActivityCompleted) {
                $completedActivityCount++;
            }

            $earnedCompletionXp += max(
                0,
                (int)($currentProgress['xp_earned'] ?? 0)
            );

            $possibleCompletionXp += max(
                0,
                (int)($currentActivity['xp_reward'] ?? 10)
            );
        }

        $statusLabel = match ((string)$lessonState['status']) {
            'completed' => 'Hoàn thành',
            'in_progress' => 'Đang học',
            default => $isUnlocked ? 'Bắt đầu' : 'Chưa mở',
        };

        $lessonUnlockMode = strtolower(
            trim((string)($lesson['unlock_mode'] ?? 'sequential_daily'))
        );
        $lessonUnlockDate = trim((string)($lesson['unlock_date'] ?? ''));

        $lockedTitle = 'Lesson này chưa được mở.';
        if (!$isUnlocked && $lessonUnlockMode === 'scheduled_date') {
            if ($lessonUnlockDate !== '') {
                try {
                    $lockedTitle = 'Mở vào ngày '
                        . (new DateTimeImmutable($lessonUnlockDate))->format('d/m/Y')
                        . '.';
                } catch (Throwable $e) {
                    $lockedTitle = 'Lesson này đang chờ ngày mở.';
                }
            } else {
                $lockedTitle = 'Lesson này chưa được đặt ngày mở.';
            }
        } elseif (!$isUnlocked) {
            $lockedTitle = 'Hoàn thành Lesson trước. Lesson tiếp theo sẽ mở vào ngày mai.';
        }
        ?>
        <?php if ($isUnlocked): ?>
        <a
            class="lesson-card"
            href="student-activities.php?<?= htmlspecialchars($query, ENT_QUOTES, 'UTF-8') ?>"
        >
        <?php else: ?>
        <div
            class="lesson-card lesson-card--locked"
            aria-disabled="true"
            title="<?= htmlspecialchars($lockedTitle, ENT_QUOTES, 'UTF-8') ?>"
        >
        <?php endif; ?>
            <span class="lesson-card__number">
                <?= htmlspecialchars((string)$lessonNumberForUrl, ENT_QUOTES, 'UTF-8') ?>
            </span>

            <span class="lesson-card__copy">
                <strong>
                    <?= htmlspecialchars((string)$lesson['title'], ENT_QUOTES, 'UTF-8') ?>
                </strong>

                <span class="lesson-card__meta">
                    <span class="lesson-card__progress">
                        <?= $lessonProgressPercent ?>%
                    </span>
                    <span class="lesson-card__track" aria-hidden="true">
                        <span
                            class="lesson-card__fill"
                            style="width:<?= $lessonProgressPercent ?>%"
                        ></span>
                    </span>
                    <span class="lesson-card__status">
                        <?= htmlspecialchars($statusLabel, ENT_QUOTES, 'UTF-8') ?>
                    </span>
                </span>
            </span>

            <span class="lesson-card__arrow" aria-hidden="true">
                <?= $isUnlocked ? '›' : '🔒' ?>
            </span>

            <?php if (
                !$isUnlocked
                && $lessonUnlockMode === 'scheduled_date'
                && $lessonUnlockDate !== ''
            ): ?>
                <span class="lesson-card__locked-note is-scheduled">
                    <?php
                    try {
                        $inlineUnlockDate = (new DateTimeImmutable($lessonUnlockDate))->format('d/m/Y');
                        echo '🔒 Mở vào ngày ' . htmlspecialchars($inlineUnlockDate, ENT_QUOTES, 'UTF-8');
                    } catch (Throwable $e) {
                        echo '🔒 Chưa đến ngày mở';
                    }
                    ?>
                </span>
            <?php endif; ?>

            <?php if ($isUnlocked && $currentLessonActivities !== []): ?>
                <span class="lesson-card__summary" aria-label="Các hoạt động">
                    <?php foreach ($currentLessonActivities as $currentActivity): ?>
                        <?php
                        $currentProgress =
                            $activityProgressById[
                                (int)$currentActivity['id']
                            ] ?? [];

                        $isActivityCompleted =
                            strtolower(
                                trim(
                                    (string)($currentProgress['status'] ?? '')
                                )
                            ) === 'completed';
                        ?>
                        <span
                            class="lesson-card__activity<?= $isActivityCompleted ? ' is-completed' : '' ?>"
                        >
                            <span class="lesson-card__activity-icon">
                                <?= $isActivityCompleted
                                    ? '✓'
                                    : studentLessonActivityIcon($currentActivity) ?>
                            </span>
                            <span class="lesson-card__activity-name">
                                <?= htmlspecialchars(
                                    studentLessonActivityLabel($currentActivity),
                                    ENT_QUOTES,
                                    'UTF-8'
                                ) ?>
                            </span>
                        </span>
                    <?php endforeach; ?>
                </span>

                <span class="lesson-card__stats">
                    <span>
                        <?= $completedActivityCount ?>
                        /
                        <?= count($currentLessonActivities) ?>
                        hoạt động
                    </span>

                    <span class="lesson-card__xp-summary">
                        <span>
                            <?= $earnedCompletionXp ?>/<?= $possibleCompletionXp ?>
                            XP hoàn thành
                        </span>

                        <?php if ($practiceCount > 0): ?>
                            <span>
                                <?= $practiceCount ?> lượt luyện lại
                                •
                                +<?= $practiceXp ?> XP
                            </span>
                        <?php endif; ?>
                    </span>
                </span>
            <?php endif; ?>
        <?php if ($isUnlocked): ?>
        </a>
        <?php else: ?>
        </div>
        <?php endif; ?>
    <?php endforeach; ?>
</section>

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