<?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'];

$homeStudent = [
    'full_name' => (string)($_SESSION['student_name'] ?? 'Học sinh'),
    'avatar_source' => 'default',
    'custom_avatar_path' => '',
];

try {
    $homeStudentStmt = $pdo->prepare(
        "SELECT full_name, avatar_source, custom_avatar_path
         FROM students
         WHERE id = ?
         LIMIT 1"
    );
    $homeStudentStmt->execute([$studentId]);
    $homeStudentRow = $homeStudentStmt->fetch(PDO::FETCH_ASSOC);

    if ($homeStudentRow) {
        $homeStudent = array_merge($homeStudent, $homeStudentRow);
    }
} catch (Throwable $e) {
    // Giữ fallback từ session để Home vẫn hoạt động nếu hồ sơ chưa đọc được.
}

$homeFullName = trim((string)($homeStudent['full_name'] ?? 'Học sinh'));

$homeNameParts = preg_split('/\s+/u', $homeFullName, -1, PREG_SPLIT_NO_EMPTY) ?: [];
if (count($homeNameParts) >= 2) {
    $homeShortName = implode(' ', array_slice($homeNameParts, -2));
} elseif ($homeNameParts !== []) {
    $homeShortName = (string)$homeNameParts[0];
} else {
    $homeShortName = 'Học sinh';
}

$homeAvatarPath = trim((string)($homeStudent['custom_avatar_path'] ?? ''));
$homeAvatarUrl = '';

if (
    (string)($homeStudent['avatar_source'] ?? '') === 'upload'
    && $homeAvatarPath !== ''
    && str_starts_with($homeAvatarPath, 'uploads/student-avatars/')
) {
    $homeAvatarUrl = '../' . ltrim($homeAvatarPath, '/');
} elseif (
    (string)($homeStudent['avatar_source'] ?? '') === 'preset'
    && $homeAvatarPath !== ''
    && str_starts_with($homeAvatarPath, 'assets/avatars/presets/')
) {
    $homeAvatarUrl = '../' . ltrim($homeAvatarPath, '/');
}

/*
 * Student Dashboard:
 * - student_learning_paths = nguồn chuẩn cho "đang học";
 * - student_content_progress = nguồn chuẩn cho tiến độ Activity/Lesson;
 * - xp_transactions = nguồn XP duy nhất.
 */
$currentLearning = null;

$pathStmt = $pdo->prepare(
    "SELECT
        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,

        (
            SELECT COUNT(*)
            FROM student_content_progress scp_l
            INNER JOIN lessons l_l
                ON l_l.id = scp_l.content_id
            INNER JOIN units u_l
                ON u_l.id = l_l.unit_id
            WHERE scp_l.student_id = slp.student_id
              AND scp_l.content_type = 'lesson'
              AND scp_l.status = 'completed'
              AND u_l.level_id = slp.level_id
        ) AS completed_lessons,

        (
            SELECT COUNT(DISTINCT scp_a.content_id)
            FROM student_content_progress scp_a
            INNER JOIN activities a_a
                ON a_a.id = scp_a.content_id
            INNER JOIN lessons l_a
                ON l_a.id = a_a.lesson_id
            INNER JOIN units u_a
                ON u_a.id = l_a.unit_id
            WHERE scp_a.student_id = slp.student_id
              AND scp_a.content_type = 'activity'
              AND scp_a.status = 'completed'
              AND u_a.level_id = slp.level_id
        ) AS completed_activities

     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
        completed_lessons DESC,
        completed_activities DESC,
        slp.last_accessed_at DESC,
        slp.id DESC
     LIMIT 1"
);
$pathStmt->execute([$studentId]);
$currentLearning = $pathStmt->fetch(PDO::FETCH_ASSOC) ?: null;

if ($currentLearning) {
    $currentLearning['lesson'] = null;
    $currentLearning['progress'] = 0;
    $currentLearning['continue_url'] = '';

    /*
     * Vào học:
     * - Book/Level đã được chọn theo nơi học nhiều nhất.
     * - Tìm Lesson completed cuối cùng trong đúng Book/Level.
     * - Chọn Lesson ngay kế tiếp theo thứ tự Unit -> Lesson.
     */
    $lessonsStmt = $pdo->prepare(
        "SELECT
            l.id AS lesson_id,
            l.lesson_number,
            l.title AS lesson_title,
            l.unit_id,
            u.unit_number,
            u.title AS unit_title,
            u.sort_order AS unit_sort_order,
            l.sort_order AS lesson_sort_order,
            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)$currentLearning['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;
        }

        $currentLearning['lesson'] = $levelLessons[$targetIndex];
        $lessonId = (int)$currentLearning['lesson']['lesson_id'];

        if ((int)($currentLearning['lesson']['is_completed'] ?? 0) === 1) {
            $currentLearning['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();

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

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

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

$xpStats = [
    'completion' => 0,
    'practice' => 0,
    'streak' => 0,
    'total' => 0,
];

$xpStmt = $pdo->prepare(
    "SELECT
        COALESCE(SUM(CASE WHEN xp_source='completion' THEN xp_change ELSE 0 END),0) AS completion_xp,
        COALESCE(SUM(CASE WHEN xp_source IN ('practice','new_best') THEN xp_change ELSE 0 END),0) AS practice_xp,
        COALESCE(SUM(CASE WHEN xp_source='streak' THEN xp_change ELSE 0 END),0) AS streak_xp,
        COALESCE(SUM(xp_change),0) AS total_xp
     FROM xp_transactions
     WHERE student_id = ?"
);
$xpStmt->execute([$studentId]);
$xpRow = $xpStmt->fetch(PDO::FETCH_ASSOC) ?: [];
$xpStats['completion'] = (int)($xpRow['completion_xp'] ?? 0);
$xpStats['practice'] = (int)($xpRow['practice_xp'] ?? 0);
$xpStats['streak'] = (int)($xpRow['streak_xp'] ?? 0);
$xpStats['total'] = (int)($xpRow['total_xp'] ?? 0);

/*
 * Learning streak hiện tại:
 * Một ngày được tính khi có ít nhất 1 Activity passed=1.
 * Chuỗi tiếp tục qua tháng; chỉ đứt khi thiếu một ngày.
 */
$currentStreakDays = 0;

try {
    $streakStmt = $pdo->prepare(
        "SELECT DISTINCT DATE(attempted_at) AS learning_date
         FROM student_activity_attempts
         WHERE student_id = ?
           AND passed = 1
           AND attempted_at < DATE_ADD(CURDATE(), INTERVAL 1 DAY)
         ORDER BY learning_date DESC"
    );
    $streakStmt->execute([$studentId]);

    $learningDates = array_values(array_filter(array_map(
        static fn($value): string => trim((string)$value),
        $streakStmt->fetchAll(PDO::FETCH_COLUMN)
    )));

    if ($learningDates !== [] && $learningDates[0] === date('Y-m-d')) {
        $currentStreakDays = 1;
        $cursorDate = new DateTimeImmutable($learningDates[0]);

        for ($i = 1, $count = count($learningDates); $i < $count; $i++) {
            $expectedDate = $cursorDate->modify('-1 day')->format('Y-m-d');

            if ($learningDates[$i] !== $expectedDate) {
                break;
            }

            $currentStreakDays++;
            $cursorDate = new DateTimeImmutable($learningDates[$i]);
        }
    }
} catch (Throwable $e) {
    $currentStreakDays = 0;
}

$bookStmt = $pdo->query(
    "SELECT id, name, slug
     FROM books
     WHERE status = 'active'
     ORDER BY id ASC"
);
$availableBooks = $bookStmt->fetchAll(PDO::FETCH_ASSOC);

$pageTitle = '';
$pageSubtitle = '';
$activeStudentNav = 'home';

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

<link rel="stylesheet" href="../assets/css/student-app.css">

<script>
/* Zalo Android WebView can apply a 2x text scale. Mark only that browser so
   the correction does not affect normal Chrome/Samsung Internet. */
(function () {
    var ua = navigator.userAgent || '';
    if (/Zalo/i.test(ua)) {
        document.documentElement.classList.add('is-zalo-webview');
    }
})();
</script>

<style>
/* Zalo WebView diagnostic showed computed root/body font-size = 32px while
   the page requests 16px. Force the root back to the normal 16px only in Zalo. */
html.is-zalo-webview {
    font-size: 16px !important;
    -webkit-text-size-adjust: none !important;
    text-size-adjust: none !important;
}
html.is-zalo-webview body {
    font-size: 16px !important;
    -webkit-text-size-adjust: none !important;
    text-size-adjust: none !important;
}

:root {
    --home-bg: #f3f8fc;
    --home-surface: #ffffff;
    --home-text: #102f49;
    --home-muted: #4f687b;
    --home-primary: #1478b8;
    --home-primary-dark: #075d9c;
    --home-soft: #e7f4ff;
    --home-border: #cedeea;
    --home-shadow: 0 7px 22px rgba(29, 80, 116, .09);
    --home-width: 520px;
    --home-nav-height: 78px;
}

* {
    box-sizing: border-box;
}

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

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

/* Mobile shell giống trang Đang học */
.student-app {
    width: min(100%, var(--home-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 {
    display: none !important;
    position: sticky !important;
    top: 0 !important;
    z-index: 40 !important;
    display: none !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-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: 132px 14px 28px !important;
}

/* Brand header cố định: logo trái + Learn • Play • Grow bên phải */
.home-logo {
    position: fixed;
    top: 0;
    left: 50%;
    z-index: 35;
    width: min(100%, var(--home-width));
    height: 122px;
    padding: 4px 14px 8px;
    background: #f7fbff;
    transform: translateX(-50%);
    overflow: hidden;
}

.home-brand-row {
    width: 100%;
    height: 100%;
    display: grid;
    grid-template-columns: 112px minmax(0,1fr) auto;
    grid-template-rows: 70px 34px;
    align-items: start;
    gap: 0 8px;
}

.home-brand-logo {
    display: block;
    width: 96px;
    max-width: 100%;
    height: auto;
    object-fit: contain;
    justify-self: start;
    align-self: start;
    grid-column: 1;
    grid-row: 1;
    transform: none;
}

.home-brand-slogan {
    min-width: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    grid-column: 1 / -1;
    grid-row: 2;
    gap: 6px;
    white-space: nowrap;
    font-size: 16.5px;
    font-weight: 900;
    line-height: 1;
    transform: none;
}

.home-brand-item {
    display: inline-flex;
    align-items: center;
    gap: 4px;
}
.home-brand-item--learn { color: #0b4f9c; }
.home-brand-item--play  { color: #ff6a00; }
.home-brand-item--grow  { color: #2ca51d; }
.home-brand-dot {
    color: #f2a900;
    font-size: 17px;
    font-weight: 900;
}
.home-brand-icon {
    font-family:"Segoe UI Emoji","Apple Color Emoji","Noto Color Emoji",sans-serif;
    font-size: 19px;
    line-height: 1;
}






.home-student {
    min-width: 0;
    display: inline-flex;
    align-items: center;
    justify-content: flex-end;
    grid-column: 3;
    grid-row: 1;
    align-self: start;
    padding-top: 8px;
    gap: 7px;
    color: #0b4f9c;
    text-decoration: none;
    -webkit-tap-highlight-color: transparent;
}

.home-student__name {
    max-width: 92px;
    overflow: hidden;
    font-size: 13px;
    font-weight: 900;
    line-height: 1.15;
    text-align: right;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.home-student__avatar {
    width: 42px;
    height: 42px;
    flex: 0 0 42px;
    display: grid;
    place-items: center;
    overflow: hidden;
    border: 2px solid #d7eafa;
    border-radius: 50%;
    background: #eef7ff;
    box-shadow: 0 2px 7px rgba(29,80,116,.10);
    font-size: 18px;
}

.home-student__avatar img {
    width: 100%;
    height: 100%;
    display: block;
    object-fit: cover;
}

@media (max-width: 430px) {
    .home-logo {
        padding-left: 12px;
        padding-right: 12px;
    }
    .home-brand-row {
        grid-template-columns: 104px minmax(0,1fr) auto;
    }
    .home-brand-logo {
        width: 92px;
    }
    .home-brand-slogan {
        gap: 4px;
        font-size: 17px;
    }
    .home-brand-icon {
        font-size: 18px;
    }
    .home-brand-dot {
        font-size: 16px;
    }
}

@media (max-width: 370px) {
    .home-brand-row {
        grid-template-columns: 94px minmax(0,1fr) auto;
    }
    .home-brand-logo {
        width: 84px;
    }
    .home-brand-slogan {
        gap: 3px;
        font-size: 14.5px;
    }
    .home-brand-icon {
        font-size: 16px;
    }
    .home-brand-dot {
        font-size: 14px;
    }
}

.continue-learning {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    margin-bottom: 12px;
    padding: 13px 15px;
    border: 1px solid #bcdcf4;
    border-radius: 18px;
    background: #ffffff;
    color: var(--home-text);
    text-decoration: none;
    box-shadow: var(--home-shadow);
    -webkit-tap-highlight-color: transparent;
}
.continue-learning:active { transform: scale(.985); }
.continue-learning__text { min-width: 0; }
.continue-learning__text strong {
    display: block;
    color: var(--home-primary-dark);
    font-size: 16px;
    line-height: 1.3;
}
.continue-learning__text span {
    display: block;
    margin-top: 3px;
    color: var(--home-muted);
    font-size: 12.5px;
}
.continue-learning__arrow {
    flex: 0 0 auto;
    color: var(--home-primary);
    font-size: 28px;
    font-weight: 750;
}

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

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

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


.home-dashboard {
    display: grid;
    gap: 10px;
    margin-bottom: 14px;
}

.home-dashboard__card {
    display: block;
    padding: 14px 15px;
    border: 1px solid var(--home-border);
    border-radius: 19px;
    background: #fff;
    color: var(--home-text);
    text-decoration: none;
    box-shadow: var(--home-shadow);
}

.home-dashboard__top {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 10px;
}

.home-dashboard__title {
    min-width: 0;
}

.home-dashboard__title strong {
    display: block;
    color: var(--home-primary-dark);
    font-size: 16px;
    line-height: 1.3;
}

.home-dashboard__title span {
    display: block;
    margin-top: 3px;
    overflow: hidden;
    color: var(--home-muted);
    font-size: 12.5px;
    line-height: 1.35;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.home-dashboard__arrow {
    flex: 0 0 auto;
    color: var(--home-primary);
    font-size: 28px;
    font-weight: 750;
}

.home-dashboard__progress {
    display: flex;
    align-items: center;
    gap: 9px;
    margin-top: 11px;
}

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

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

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

.home-xp {
    display: grid;
    grid-template-columns: 78px minmax(0,1fr);
    align-items: center;
    gap: 12px;
    padding: 13px 15px;
    border: 1px solid #f1df9c;
    border-radius: 19px;
    background: #fffdf4;
    box-shadow: var(--home-shadow);
}

.home-xp__total {
    text-align: center;
}

.home-xp__total span {
    display: block;
    font-size: 24px;
    line-height: 1;
}

.home-xp__total strong {
    display: block;
    margin-top: 5px;
    color: #a56a00;
    font-size: 18px;
}

.home-xp__body strong {
    display: block;
    color: #6c4b00;
    font-size: 14px;
}

.home-xp__body span {
    display: block;
    margin-top: 4px;
    color: #8a7650;
    font-size: 12px;
    line-height: 1.4;
}

.home-streak {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    margin-top: 7px;
    padding: 6px 9px;
    border-radius: 999px;
    background: #fff4dc;
    color: #9a5b00;
    font-size: 12.5px;
    font-weight: 850;
    line-height: 1.2;
}

.book-list {
    display: grid;
    gap: 12px;
}

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

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

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

.book-card__body {
    min-width: 0;
}

.book-card__title {
    display: block;
    overflow: hidden;
    color: var(--home-primary-dark);
    font-size: 17px;
    font-weight: 850;
    line-height: 1.3;
    text-overflow: ellipsis;
    white-space: nowrap;
}

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

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

.book-empty {
    padding: 28px 18px;
    border: 1px dashed var(--home-border);
    border-radius: 19px;
    background: var(--home-surface);
    color: var(--home-muted);
    text-align: center;
}

/* Bottom nav cùng khung mobile */
.student-nav {
    position: fixed !important;
    z-index: 9999 !important;
    left: 50% !important;
    bottom: 0 !important;
    width: min(100%, var(--home-width)) !important;
    min-height: var(--home-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: #40576a !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: 12px !important;
    font-weight: 800 !important;
    white-space: nowrap !important;
    text-overflow: ellipsis !important;
}

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

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

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

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

    .home-intro {
        padding: 14px;
    }

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

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

    .book-card__title {
        font-size: 16px;
    }
}

/* UI polish: clearer, brighter and easier to read on phones */
.student-app::before,.student-app::after{display:none!important}
.home-dashboard__card{padding:16px}
.home-dashboard__title strong{font-size:17.5px;font-weight:900;color:#006eb8}
.home-dashboard__title span{font-size:14.5px;font-weight:700;color:#365a73}
.home-dashboard__percent{font-size:13.5px;font-weight:900;color:#0067ad}

.home-xp{padding:15px 16px}
.home-xp__total strong{font-size:19px;font-weight:900;color:#a96100}
.home-xp__body strong{font-size:17px;font-weight:900;color:#6b4600}
.home-xp__body span{font-size:14px;font-weight:700;color:#735f34;line-height:1.45}

.home-intro h2{font-size:19.5px;font-weight:900;color:#0b527f}
.home-intro p{font-size:15px;font-weight:700;color:#365a73}

.book-card__title{font-size:18.5px;font-weight:900;color:#0068ad}
.book-card__meta{font-size:14.5px;font-weight:700;color:#365a73}

.student-nav__label{font-size:12.5px!important;font-weight:850!important;color:inherit!important}

</style>

<div class="home-logo">
    <div class="home-brand-row">
        <img class="home-brand-logo" src="../assets/images/englishspeak-logo.png" alt="EnglishSpeak">
        <div class="home-brand-slogan" aria-label="Learn Play Grow">
            <span class="home-brand-item home-brand-item--learn"><span class="home-brand-icon" aria-hidden="true">📖</span>Learn</span>
            <span class="home-brand-dot" aria-hidden="true">•</span>
            <span class="home-brand-item home-brand-item--play"><span class="home-brand-icon" aria-hidden="true">🎮</span>Play</span>
            <span class="home-brand-dot" aria-hidden="true">•</span>
            <span class="home-brand-item home-brand-item--grow"><span class="home-brand-icon" aria-hidden="true">🌱</span>Grow together!</span>
        </div>

        <a class="home-student" href="student-profile.php" aria-label="Mở hồ sơ">
            <span class="home-student__name"><?= htmlspecialchars($homeShortName, ENT_QUOTES, 'UTF-8') ?></span>
            <span class="home-student__avatar" aria-hidden="true">
                <?php if ($homeAvatarUrl !== ''): ?>
                    <img src="<?= htmlspecialchars($homeAvatarUrl, ENT_QUOTES, 'UTF-8') ?>" alt="">
                <?php else: ?>
                    👤
                <?php endif; ?>
            </span>
        </a>
    </div>
</div>

<section class="home-dashboard">
<?php if ($currentLearning): ?>
    <?php
        $homeLesson = $currentLearning['lesson'] ?? null;
        $homeProgress = (int)($currentLearning['progress'] ?? 0);
        $homeAction = 'Vào học';
    ?>
    <a class="home-dashboard__card" href="<?= htmlspecialchars((string)$currentLearning['continue_url'], ENT_QUOTES, 'UTF-8') ?>">
        <div class="home-dashboard__top">
            <span class="home-dashboard__title">
                <strong>▶ Vào học</strong>
                <span>
                    <?= htmlspecialchars(
                        (string)$currentLearning['book_name'] . ' • ' . (string)$currentLearning['level_name'],
                        ENT_QUOTES,
                        'UTF-8'
                    ) ?>
                </span>
            </span>
            <span class="home-dashboard__arrow" aria-hidden="true">›</span>
        </div>

        <?php if ($homeLesson): ?>
            <div class="home-dashboard__title" style="margin-top:8px;">
                <span style="color:var(--home-text);font-weight:800;">
                    <?= htmlspecialchars(
                        (string)$homeLesson['unit_number'] . ' • ' . (string)$homeLesson['lesson_title'],
                        ENT_QUOTES,
                        'UTF-8'
                    ) ?>
                </span>
            </div>

            <div class="home-dashboard__progress">
                <span class="home-dashboard__track" aria-hidden="true">
                    <span class="home-dashboard__fill" style="width:<?= $homeProgress ?>%"></span>
                </span>
                <span class="home-dashboard__percent"><?= $homeProgress ?>%</span>
            </div>
        <?php endif; ?>
    </a>
<?php endif; ?>

<?php if ($xpStats['total'] > 0): ?>
<div class="home-xp">
    <div class="home-xp__total">
        <span aria-hidden="true">⭐</span>
        <strong><?= $xpStats['total'] ?> XP</strong>
    </div>
    <div class="home-xp__body">
        <strong>My XP</strong>
        <span>
            <?= $xpStats['completion'] ?> XP hoàn thành
            •
            <?= $xpStats['practice'] ?> XP luyện tập
            <?php if ($xpStats['streak'] > 0): ?>
                • <?= $xpStats['streak'] ?> XP chuỗi
            <?php endif; ?>
        </span>

        <?php if ($currentStreakDays > 0): ?>
            <span class="home-streak">
                🔥 <?= $currentStreakDays ?> ngày liên tiếp
            </span>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>
</section>

<section class="home-intro">
    <h2>📚 Chọn bộ sách</h2>
</section>

<div class="book-list">
    <?php if ($availableBooks === []): ?>
        <div class="book-empty">
            Hiện chưa có bộ sách nào.
        </div>
    <?php else: ?>
        <?php foreach ($availableBooks as $book): ?>
            <a
                class="book-card"
                href="<?= htmlspecialchars(
                    'student-levels.php?' . http_build_query([
                        'book' => (string)$book['slug'],
                    ]),
                    ENT_QUOTES,
                    'UTF-8'
                ) ?>"
            >
                <span class="book-card__cover" aria-hidden="true">📘</span>

                <span class="book-card__body">
                    <span class="book-card__title">
                        <?= htmlspecialchars(
                            (string)$book['name'],
                            ENT_QUOTES,
                            'UTF-8'
                        ) ?>
                    </span>

                </span>

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

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

<style>
/* EnglishSpeak Home — white base + pastel accent + logo-blue typography */
:root{
    --home-bg:#ffffff;
    --home-surface:#ffffff;
    --home-text:#0b4f9c;
    --home-muted:#315d82;
    --logo-blue:#0b4f9c;
    --logo-blue-soft:#315d82;
}
html,body{background:#ffffff!important;color:var(--logo-blue)!important}
.student-app{background:#ffffff!important;box-shadow:0 0 24px rgba(20,60,90,.06)!important}
.home-logo{background:#ffffff!important}

.home-dashboard__card{background:#ffffff!important;color:var(--logo-blue)!important}
.home-dashboard__title strong{color:var(--logo-blue)!important}
.home-dashboard__top .home-dashboard__title strong{
    font-size:20px!important;
    line-height:1.25!important;
    font-weight:900!important;
}
.home-dashboard__title span{color:var(--logo-blue-soft)!important}

.home-xp__body strong{color:var(--logo-blue)!important}
.home-xp__body span{color:var(--logo-blue-soft)!important}

.home-intro{
    background:#eef7ff!important;
    border-color:#cfe4f5!important;
}
.home-intro h2{color:var(--logo-blue)!important}
.home-intro p{color:var(--logo-blue-soft)!important}

.book-card{background:#ffffff!important;color:var(--logo-blue)!important}
.book-card__title{color:var(--logo-blue)!important}
.book-card__meta{color:var(--logo-blue-soft)!important}

.student-nav{background:#ffffff!important}

/* Bottom menu: dùng cùng hệ màu chữ xanh EnglishSpeak */
.student-nav__item:not(.is-active){
    color:var(--logo-blue-soft)!important;
}
.student-nav__item.is-active{
    color:var(--logo-blue)!important;
}
.student-nav__label{
    color:inherit!important;
    font-weight:850!important;
}

/* Cân lại header: logo trái - slogan giữa - học sinh phải */
.home-brand-row {
    grid-template-columns: 104px minmax(0, 1fr) 104px;
    column-gap: 4px;
}
.home-brand-logo {
    justify-self: start;
}
.home-student {
    width: 104px;
    justify-self: end;
    justify-content: flex-end;
}
.home-brand-slogan {
    justify-self: center;
}

@media (max-width: 430px) {
    .home-brand-row {
        grid-template-columns: 98px minmax(0, 1fr) 98px;
    }
    .home-student { width: 98px; }
}

@media (max-width: 370px) {
    .home-brand-row {
        grid-template-columns: 90px minmax(0, 1fr) 90px;
    }
    .home-student { width: 90px; }
}

/* Header final:
   - Logo stays top-left.
   - Student name + avatar stays top-right.
   - Student name is shown fully.
   - Slogan is centered only in the area from the logo's RIGHT edge
     to the RIGHT edge of the mobile screen. */
.home-student {
    width: auto !important;
    min-width: max-content !important;
    justify-self: end !important;
    justify-content: flex-end !important;
}
.home-student__name {
    max-width: none !important;
    overflow: visible !important;
    text-overflow: clip !important;
    white-space: nowrap !important;
}

/* Logo is 96px wide; home-logo has 14px horizontal padding.
   So the slogan region starts at 14 + 96 = 110px and ends at the
   right inner edge of the mobile shell. */
.home-brand-slogan {
    position: absolute !important;
    left: 110px !important;
    right: 14px !important;
    top: 78px !important;
    width: auto !important;
    display: flex !important;
    justify-content: center !important;
    transform: none !important;
}

@media (max-width: 430px) {
    /* Mobile: logo is 92px and side padding is 12px. */
    .home-brand-slogan {
        left: 104px !important;
        right: 12px !important;
    }
}

@media (max-width: 370px) {
    /* Small mobile: logo is 84px; keep the same 12px side padding. */
    .home-brand-slogan {
        left: 96px !important;
        right: 12px !important;
    }
}


/* Slogan final: căn giữa trong khoảng từ mép phải logo đến mép trái avatar. */
.home-brand-slogan {
    left: 110px !important;   /* 14px padding + logo 96px */
    right: 63px !important;   /* 14px padding + avatar 42px + 7px gap */
}

@media (max-width: 430px) {
    .home-brand-slogan {
        left: 104px !important;  /* 12px + logo 92px */
        right: 61px !important;  /* 12px + avatar 42px + 7px */
    }
}

@media (max-width: 370px) {
    .home-brand-slogan {
        left: 96px !important;   /* 12px + logo 84px */
        right: 61px !important;
    }
}

</style>
