<?php
require_once __DIR__ . '/includes/config.php';
requireLogin();

$user        = currentUser();
$currentPage = 'quiz';
$pageTitle   = 'Quiz – SPACE';

// Fetch quiz decks
$stmt = db()->prepare('
    SELECT id, title, subject, difficulty, question_count, quiz_type,
           is_timed, seconds_per_question, source, created_at
    FROM quiz_decks WHERE user_id = ? ORDER BY created_at DESC LIMIT 20
');
$stmt->execute([$user['id']]);
$decks = $stmt->fetchAll();

// Fetch uploaded docs
$stmt2 = db()->prepare('SELECT id, original_name, file_size, created_at FROM uploaded_docs WHERE user_id=? ORDER BY created_at DESC LIMIT 12');
$stmt2->execute([$user['id']]);
$docs = $stmt2->fetchAll();

// ── Colour helpers ─────────────────────────────────────
function getFileColor(string $name): string {
    $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
    return match($ext) {
        'pdf'        => '#ef4444',
        'docx','doc' => '#2563eb',
        'xlsx','xls' => '#16a34a',
        'pptx','ppt' => '#ea580c',
        'txt','md'   => '#6b7280',
        'csv'        => '#0891b2',
        default      => '#9333ea',
    };
}
function diffColor(string $d): string {
    return match($d) { 'easy'=>'#22c55e','medium'=>'#f59e0b','hard'=>'#ef4444',default=>'#6b7280' };
}
function diffBg(string $d): string {
    return match($d) { 'easy'=>'#d1fae5','medium'=>'#fef3c7','hard'=>'#fee2e2',default=>'#f3f4f6' };
}
function typeColor(string $t): string {
    return match($t) {
        'multiple_choice'=>'#3b82f6','identification'=>'#8b5cf6',
        'true_false'=>'#f59e0b','short_answer'=>'#ec4899','all'=>'#6366f1',default=>'#6b7280',
    };
}
function typeBg(string $t): string {
    return match($t) {
        'multiple_choice'=>'#dbeafe','identification'=>'#ede9fe',
        'true_false'=>'#fef3c7','short_answer'=>'#fce7f3','all'=>'#e0e7ff',default=>'#f3f4f6',
    };
}
function typeLabel(string $t): string {
    return match($t) {
        'multiple_choice'=>'Multiple Choice','identification'=>'Identification',
        'true_false'=>'True/False','short_answer'=>'Short Answer','all'=>'Mixed',default=>$t,
    };
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, interactive-widget=resizes-content">
<title>Quiz – SPACE</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/boxicons@2.1.4/css/boxicons.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<meta name="csrf-token" content="<?= e(csrfToken()) ?>">
<style>
/* ══════ ROOT ══════ */
:root {
  --bg:#e4e4e4;--light:#f8f8f8;--dark:#bebebe;
  --text:#1a1a1a;--muted:#888;
  --blue:#0239eb;--green:#22c55e;--red:#ef4444;--amber:#f59e0b;
  --neu-out:6px 6px 12px var(--dark),-6px -6px 12px var(--light);
  --neu-in:inset 4px 4px 8px var(--dark),inset -4px -4px 8px var(--light);
  --neu-sm:3px 3px 6px var(--dark),-3px -3px 6px var(--light);
  --neu-xs:2px 2px 4px var(--dark),-2px -2px 4px var(--light);
  --r-sm:12px;--r-md:16px;--r-lg:22px;--r-xl:28px;
  --font:'Poppins',sans-serif;
}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
html,body{width:100%;height:100dvh;background:var(--bg);font-family:var(--font);overflow:hidden;position:fixed;inset:0;color:var(--text);-webkit-tap-highlight-color:transparent}
a{text-decoration:none;color:inherit}
button{font-family:var(--font);cursor:pointer;border:none;background:none}
::-webkit-scrollbar{display:none}
*{-ms-overflow-style:none;scrollbar-width:none}

/* ══════ SHELL ══════ */
.shell{width:100%;height:100dvh;display:flex;flex-direction:column;background:var(--bg);overflow:hidden;max-width:480px;margin:0 auto;box-shadow:0 0 40px rgba(0,0,0,.08)}

/* ══════ TOP BAR ══════ */
.top-bar{display:flex;align-items:center;justify-content:space-between;padding:clamp(10px,2dvh,16px) 18px clamp(8px,1.5dvh,12px);flex-shrink:0;position:relative;z-index:30}
.icon-btn{width:42px;height:42px;border-radius:50%;background:var(--bg);box-shadow:var(--neu-sm);display:flex;align-items:center;justify-content:center;color:var(--text);font-size:18px}
.icon-btn:active{box-shadow:var(--neu-in)}
.logo-pill{width:70px;height:70px;border-radius:50%;background:var(--bg);box-shadow:var(--neu-sm);display:flex;align-items:center;justify-content:center;margin:0 auto;cursor:pointer}
.logo-pill:active{box-shadow:var(--neu-in)}
.logo-pill img{width:50px;height:50px}
.kebab-wrap{position:relative}
.kebab-menu{position:absolute;top:50px;right:0;background:var(--bg);border-radius:var(--r-md);box-shadow:var(--neu-out);padding:8px;display:none;flex-direction:column;gap:2px;z-index:200;min-width:170px;border:1px solid #d8d8d8}
.kebab-menu.open{display:flex}
.kebab-menu a,.kebab-menu button{display:flex;align-items:center;gap:8px;padding:9px 13px;font-size:12px;font-weight:500;color:var(--text);border-radius:8px;transition:background .12s;white-space:nowrap}
.kebab-menu a:hover,.kebab-menu button:hover{background:rgba(0,0,0,.04)}
.kebab-menu i{font-size:14px;color:var(--muted);width:16px}

/* ══════ PAGE HEADING ══════ */
.page-heading{padding:0 18px clamp(4px,1dvh,12px);flex-shrink:0}
.page-heading h1{font-size:clamp(18px,5vw,22px);font-weight:800;line-height:1.1}
.page-heading p{font-size:clamp(9px,2.5vw,11px);color:var(--muted);margin-top:2px}

/* ══════ MAIN STAGE ══════ */
.main-stage{flex:1;min-height:0;display:flex;flex-direction:column;overflow:hidden;gap:clamp(4px,1.5dvh,16px);padding:clamp(4px,1dvh,12px) 0}
.section{flex-shrink:0;padding:0 18px clamp(10px,2dvh,20px)}
.section-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:10px}
.section-title{display:flex;align-items:center;gap:6px;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.08em}
.section-title i{font-size:14px;color:var(--muted)}
.section-link{font-size:10px;font-weight:600;color:var(--muted)}
.h-scroll{display:flex;gap:12px;overflow-x:auto;overflow-y:visible;padding-bottom:4px;scroll-snap-type:x mandatory;-webkit-overflow-scrolling:touch}
.h-scroll>*{scroll-snap-align:start}

/* ══════ GENERATE BUTTON CARD ══════ */
.gen-btn-card{width:100%;height:clamp(130px,16dvh,180px);background:var(--bg);border-radius:var(--r-xl);box-shadow:var(--neu-out);padding:clamp(14px,3vw,20px);border:2px dashed var(--dark);cursor:pointer;display:grid;place-items:center;gap:10px;transition:.15s}
.gen-btn-card:active{box-shadow:var(--neu-in);transform:scale(.99)}
.gen-btn-title{font-size:clamp(13px,3.5vw,16px);font-weight:700}
.gen-btn-sub{font-size:clamp(10px,2.5vw,12px);color:var(--muted);text-align:center}

/* ══════ DECK CARDS ══════ */
.deck-card{flex-shrink:0;width:150px;background:var(--bg);border-radius:var(--r-lg);box-shadow:var(--neu-out);padding:14px 12px;cursor:pointer;transition:.15s;display:flex;flex-direction:column;gap:8px;position:relative;overflow:hidden}
.deck-card:active{box-shadow:var(--neu-in);transform:scale(.98)}
.deck-card-top{display:flex;align-items:flex-start;justify-content:space-between}
.deck-icon-wrap{width:38px;height:38px;border-radius:10px;background:var(--bg);box-shadow:var(--neu-xs);display:flex;align-items:center;justify-content:center;font-size:18px}
.deck-tag{font-size:8px;font-weight:700;padding:3px 7px;border-radius:20px;text-transform:uppercase;letter-spacing:.04em}
.deck-nums{display:flex;align-items:baseline;gap:2px}
.deck-nums .big{font-size:26px;font-weight:300;line-height:1}
.deck-nums .slash{font-size:13px;color:var(--muted)}
.deck-sub-lbl{font-size:9px;color:var(--muted);text-transform:uppercase;letter-spacing:.04em;margin-top:2px}
.deck-title-txt{font-size:11px;font-weight:600;line-height:1.3;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.deck-del{position:absolute;bottom:10px;right:10px;width:24px;height:24px;border-radius:50%;background:var(--bg);box-shadow:var(--neu-xs);display:flex;align-items:center;justify-content:center;color:#bbb;font-size:11px;opacity:0;transition:opacity .2s}
.deck-card:hover .deck-del{opacity:1}
.deck-card-add{flex-shrink:0;width:150px;background:var(--bg);border-radius:var(--r-lg);box-shadow:var(--neu-in);padding:14px 12px;cursor:pointer;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;color:var(--muted);border:2px dashed var(--dark)}
.deck-card-add i{font-size:22px}
.deck-card-add span{font-size:10px;font-weight:600;text-align:center}

/* ══════ DOC CARDS ══════ */
.doc-upload-card{flex-shrink:0;width:100px;background:var(--bg);border-radius:var(--r-md);border:2px dashed var(--dark);display:flex;flex-direction:column;align-items:center;justify-content:center;gap:6px;padding:12px 8px;cursor:pointer;transition:.15s}
.doc-upload-card:active{box-shadow:var(--neu-in)}
.doc-upload-card i{font-size:22px;color:var(--muted)}
.doc-upload-card span{font-size:9px;font-weight:600;color:var(--muted);text-align:center;line-height:1.3}
.doc-card{flex-shrink:0;width:100px;background:var(--bg);border-radius:var(--r-md);box-shadow:var(--neu-sm);padding:12px 10px;cursor:pointer;transition:.15s;display:flex;flex-direction:column;align-items:center;gap:6px;text-align:center}
.doc-card:active{box-shadow:var(--neu-in);transform:scale(.97)}
.doc-file-icon{width:44px;height:52px;border-radius:6px;display:flex;align-items:center;justify-content:center;position:relative;font-size:11px;font-weight:800;color:#fff;letter-spacing:.5px}
.doc-file-icon::before{content:'';position:absolute;top:0;right:0;width:12px;height:12px;background:rgba(255,255,255,.3);clip-path:polygon(100% 0,0 0,100% 100%)}
.doc-card-name{font-size:9px;font-weight:600;color:var(--text);line-height:1.3;word-break:break-all;max-height:28px;overflow:hidden}

/* ══════ MODAL BACKDROPS / SHEETS ══════ */
.modal-backdrop{position:fixed;inset:0;background:rgba(228,228,228,.7);backdrop-filter:blur(8px);z-index:500;display:flex;align-items:flex-end;justify-content:center;opacity:0;pointer-events:none;transition:opacity .25s}
.modal-backdrop.open{opacity:1;pointer-events:all}
.modal-sheet{width:100%;max-width:480px;background:var(--bg);border-radius:var(--r-xl) var(--r-xl) 0 0;box-shadow:0 -8px 32px rgba(0,0,0,.12);padding:0 0 clamp(20px,5vw,30px);transform:translateY(100%);transition:transform .3s cubic-bezier(.25,.8,.25,1);max-height:90dvh;overflow-y:auto}
.modal-backdrop.open .modal-sheet{transform:translateY(0)}
.modal-handle{width:36px;height:4px;border-radius:2px;background:var(--dark);margin:12px auto 20px}
.modal-title{font-size:16px;font-weight:800;text-align:center;margin-bottom:18px;padding:0 20px}
.modal-body{padding:0 20px}
.modal-footer{padding:14px 20px 0;display:flex;gap:10px}
.modal-input{width:100%;padding:12px 16px;border-radius:var(--r-sm);background:var(--bg);border:none;outline:none;box-shadow:var(--neu-in);font-family:var(--font);font-size:13px;color:var(--text);margin-bottom:14px}
.modal-input::placeholder{color:#aaa}
.modal-label{font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:.08em;color:var(--muted);margin-bottom:8px;display:block}

.modal-btn{flex:1;padding:13px;border-radius:50px;background:var(--bg);box-shadow:var(--neu-sm);font-size:13px;font-weight:700;color:var(--text);transition:.15s;display:flex;align-items:center;justify-content:center;gap:6px}
.modal-btn:active{box-shadow:var(--neu-in);transform:scale(.99)}
.modal-btn.primary{background:var(--text);color:var(--bg);box-shadow:none}
.modal-btn i{font-size:14px}

/* Count row */
.count-row{display:flex;gap:8px;margin-bottom:14px}
.count-btn{flex:1;padding:10px 6px;border-radius:var(--r-sm);background:var(--bg);box-shadow:var(--neu-sm);font-size:12px;font-weight:700;color:var(--muted);transition:.15s}
.count-btn.on{box-shadow:var(--neu-in);color:var(--text)}

/* Toggle buttons row (type/diff/secs) */
.tog-row{display:flex;gap:8px;margin-bottom:14px;flex-wrap:wrap}
.tog-btn{flex:1;min-width:60px;padding:9px 6px;border-radius:var(--r-sm);background:var(--bg);box-shadow:var(--neu-sm);font-size:10px;font-weight:700;color:var(--muted);transition:.15s;border:2px solid transparent;display:flex;align-items:center;justify-content:center;gap:4px}
.tog-btn:active{transform:scale(.97)}
.tog-btn i{font-size:13px}
/* Difficulty selected states */
.tog-btn[data-d="easy"].on   {box-shadow:var(--neu-in);color:#22c55e;border-color:#22c55e}
.tog-btn[data-d="medium"].on {box-shadow:var(--neu-in);color:#f59e0b;border-color:#f59e0b}
.tog-btn[data-d="hard"].on   {box-shadow:var(--neu-in);color:#ef4444;border-color:#ef4444}
/* Type selected states */
.tog-btn[data-t].on{box-shadow:var(--neu-in);color:var(--blue);border-color:var(--blue)}
/* Secs selected states */
.tog-btn[data-s].on{box-shadow:var(--neu-in);color:var(--text)}

/* Timer switch row */
.timer-row{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px}
.timer-lbl{font-size:12px;font-weight:600}
.sw{position:relative;width:50px;height:28px;border-radius:14px;background:var(--dark);transition:.2s;cursor:pointer;border:none}
.sw.on{background:var(--green)}
.sw-knob{position:absolute;top:3px;left:3px;width:22px;height:22px;border-radius:50%;background:var(--light);box-shadow:var(--neu-xs);transition:.2s;pointer-events:none}
.sw.on .sw-knob{left:25px}

/* Doc selected display */
.doc-sel-row{display:flex;align-items:center;gap:12px;padding:12px 14px;border-radius:var(--r-md);background:var(--bg);box-shadow:var(--neu-sm);margin-bottom:14px}
.doc-sel-icon{width:40px;height:46px;border-radius:6px;display:flex;align-items:center;justify-content:center;font-size:10px;font-weight:800;color:#fff;flex-shrink:0;position:relative}
.doc-sel-icon::before{content:'';position:absolute;top:0;right:0;width:10px;height:10px;background:rgba(255,255,255,.3);clip-path:polygon(100% 0,0 0,100% 100%)}
.doc-sel-name{font-size:12px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;flex:1;overflow:hidden}
.doc-sel-sub{font-size:9px;color:var(--muted);margin-top:2px}

/* Spinner */
.gen-spinner{display:flex;flex-direction:column;align-items:center;gap:12px;padding:24px 0 10px}
.gen-spinner p{font-size:13px;font-weight:600;text-align:center}
.gen-spinner small{font-size:11px;color:var(--muted);text-align:center;min-height:16px}
.spin-dots{display:flex;gap:6px;margin-top:4px}
.spin-dot{width:8px;height:8px;border-radius:50%;background:var(--muted);animation:blink 1.4s infinite both}
.spin-dot:nth-child(2){animation-delay:.2s}
.spin-dot:nth-child(3){animation-delay:.4s}
@keyframes blink{0%,80%,100%{opacity:.2}40%{opacity:1}}

/* ══════ STUDY OVERLAY ══════ */
.study-overlay{position:fixed;inset:0;background:var(--bg);z-index:400;display:flex;flex-direction:column;opacity:0;pointer-events:none;transition:opacity .2s}
.study-overlay.open{opacity:1;pointer-events:all}
.study-topbar{display:flex;align-items:center;justify-content:space-between;padding:14px 18px;flex-shrink:0}
.study-info{text-align:center;flex:1;overflow:hidden}
.study-info h2{font-size:13px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.study-info p{font-size:10px;color:var(--muted)}
.prog-ring-wrap{position:relative;width:38px;height:38px;flex-shrink:0}
.prog-ring-wrap svg{transform:rotate(-90deg)}
.prog-ring-bg{fill:none;stroke:var(--dark);stroke-width:4}
.prog-ring-fill{fill:none;stroke:var(--text);stroke-width:4;stroke-linecap:round;transition:stroke-dashoffset .4s}
.study-progress{height:6px;margin:0 18px 10px;border-radius:6px;background:var(--bg);box-shadow:var(--neu-in);overflow:hidden;flex-shrink:0}
.study-progress-fill{height:100%;border-radius:6px;background:linear-gradient(90deg,var(--blue),#6366f1);transition:width .4s}
.study-timer{font-size:clamp(18px,5vw,24px);font-weight:700;color:var(--text);text-align:center;padding:0 18px 8px;flex-shrink:0}
.study-timer.warn{color:var(--amber)}
.study-timer.danger{color:var(--red);animation:pulse .6s infinite alternate}
@keyframes pulse{from{opacity:1}to{opacity:.4}}

/* Question card */
.study-stage{flex:1;min-height:0;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:clamp(8px,2dvh,16px) clamp(12px,4vw,18px);gap:clamp(10px,2dvh,16px);overflow-y:auto}
.question-card{width:100%;max-width:380px;background:var(--bg);border-radius:var(--r-xl);box-shadow:var(--neu-out);padding:20px 18px}
.q-type-badge{display:inline-block;font-size:9px;font-weight:700;padding:4px 10px;border-radius:12px;text-transform:uppercase;margin-bottom:12px;letter-spacing:.08em}
.q-text{font-size:clamp(14px,4vw,17px);font-weight:600;line-height:1.5;color:var(--text);margin-bottom:18px}

/* Options */
.options-list{display:flex;flex-direction:column;gap:10px}
.option-btn{width:100%;padding:12px 14px;border-radius:var(--r-md);background:var(--bg);box-shadow:var(--neu-sm);border:2px solid transparent;font-size:13px;font-weight:500;color:var(--text);text-align:left;transition:.15s;display:flex;align-items:center;gap:10px}
.option-btn:active{transform:scale(.98)}
.option-btn.selected{border-color:var(--blue);box-shadow:var(--neu-in)}
.option-btn.correct{border-color:var(--green)!important;background:#f0fdf4;box-shadow:none}
.option-btn.wrong{border-color:var(--red)!important;background:#fef2f2;box-shadow:none}
.opt-circle{width:22px;height:22px;border-radius:50%;background:var(--bg);box-shadow:var(--neu-xs);display:flex;align-items:center;justify-content:center;font-size:10px;font-weight:700;color:var(--muted);flex-shrink:0;transition:.15s}
.option-btn.selected .opt-circle{background:var(--blue);color:#fff;box-shadow:none}
.option-btn.correct .opt-circle{background:var(--green);color:#fff;box-shadow:none}
.option-btn.wrong   .opt-circle{background:var(--red);color:#fff;box-shadow:none}

/* Text input */
.answer-input{width:100%;padding:13px 16px;border-radius:var(--r-md);background:var(--bg);box-shadow:var(--neu-in);border:none;outline:none;font-family:var(--font);font-size:14px;font-weight:500;color:var(--text);text-align:center;transition:.15s}
.answer-input:focus{box-shadow:inset 5px 5px 10px var(--dark),inset -5px -5px 10px var(--light)}
.submit-ans-btn{width:100%;padding:13px;border-radius:50px;background:var(--bg);box-shadow:var(--neu-out);font-size:13px;font-weight:700;color:var(--blue);transition:.15s;margin-top:10px;display:flex;align-items:center;justify-content:center;gap:6px}
.submit-ans-btn:active{box-shadow:var(--neu-in);transform:scale(.98)}

/* Feedback card */
.feedback-card{width:100%;max-width:380px;background:var(--bg);border-radius:var(--r-xl);box-shadow:var(--neu-out);padding:24px 20px;text-align:center}
.fb-icon{font-size:44px;margin-bottom:10px}
.fb-title{font-size:16px;font-weight:700;margin-bottom:6px}
.fb-answer{font-size:12px;color:var(--muted);margin-bottom:12px;line-height:1.6}
.fb-answer strong{color:var(--text)}
.fb-expl{background:var(--bg);box-shadow:var(--neu-in);padding:12px;border-radius:var(--r-md);font-size:12px;color:var(--text);line-height:1.5;text-align:left;margin-bottom:14px}
.fb-expl strong{display:block;font-size:10px;color:var(--muted);margin-bottom:4px;text-transform:uppercase;letter-spacing:.08em}
.fb-next-btn{width:100%;padding:12px;border-radius:50px;background:var(--text);color:var(--bg);font-size:13px;font-weight:700;display:flex;align-items:center;justify-content:center;gap:6px}
.fb-next-btn:active{opacity:.85}

/* Study controls */
.study-controls{display:flex;gap:10px;width:100%;max-width:320px;flex-shrink:0;padding:0 18px clamp(10px,2dvh,16px);margin:0 auto}
.study-btn{flex:1;padding:12px;border-radius:50px;background:var(--bg);box-shadow:var(--neu-out);font-size:12px;font-weight:700;display:flex;align-items:center;justify-content:center;gap:5px;transition:.15s}
.study-btn:active{box-shadow:var(--neu-in);transform:scale(.98)}
.study-btn.miss{color:var(--red)}
.study-btn.got{color:var(--green)}
.study-btn i{font-size:15px}

/* Results */
.results-screen{position:absolute;inset:0;background:var(--bg);display:flex;flex-direction:column;align-items:center;justify-content:center;padding:clamp(16px,4vw,24px) clamp(12px,3vw,20px);gap:clamp(8px,2vw,12px);opacity:0;pointer-events:none;transition:opacity .3s;z-index:10}
.results-screen.open{opacity:1;pointer-events:all}
.results-emoji{font-size:clamp(36px,10vw,48px)}
.results-score{font-size:clamp(36px,12vw,56px);font-weight:700;line-height:1}
.results-msg{font-size:clamp(11px,3vw,13px);color:var(--muted);margin-bottom:4px;text-align:center}
.results-grid{display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px;width:100%;max-width:320px}
.res-stat{background:var(--bg);border-radius:var(--r-md);padding:12px;box-shadow:var(--neu-sm);text-align:center}
.res-stat-val{font-size:22px;font-weight:300}
.res-stat-lbl{font-size:9px;color:var(--muted);text-transform:uppercase;letter-spacing:.04em}
.results-btns{display:flex;gap:10px;width:100%;max-width:320px;margin-top:8px}

/* Toast */
.toast-wrap{position:fixed;top:18px;left:50%;transform:translateX(-50%);z-index:9999;display:flex;flex-direction:column;align-items:center;gap:6px;pointer-events:none}
.toast{background:var(--text);color:var(--bg);padding:10px 18px;border-radius:50px;font-size:12px;font-weight:600;box-shadow:var(--neu-out);white-space:nowrap;animation:toastIn .25s ease both}
.toast.good{background:#065f46}
.toast.bad{background:#991b1b}
@keyframes toastIn{from{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:none}}

/* Desktop */
@media(min-width:481px){
  body{display:flex;align-items:center;justify-content:center}
  .shell{border-radius:var(--r-xl);overflow:hidden;height:min(860px,100dvh)}
  .modal-sheet{border-radius:var(--r-xl)}
  .study-overlay{border-radius:var(--r-xl);position:absolute;inset:unset;width:480px;height:min(860px,100dvh)}
}
@media(max-height:680px){
  .page-heading h1{font-size:18px}
  .section{padding-bottom:10px}
  .deck-card{width:130px}
  .doc-card{width:85px}
  .gen-btn-card{height:110px}
}
</style>
</head>
<body>
<div class="shell">

  <!-- TOP BAR -->
  <div class="top-bar">
<button class="icon-btn" onclick="window.history.back()" title="Go Back">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" width="18"><path d="M19 12H5M12 19l-7-7 7-7"/></svg>
    </button>
        <div class="logo-pill" onclick="location.href='dashboard.php'">
      <img src="assets/img/logo.svg" alt="S">
    </div>
    <div class="kebab-wrap">
      <button class="icon-btn" id="kebab-btn"><i class='bx bx-dots-vertical-rounded'></i></button>
      <div class="kebab-menu" id="kebab-menu">
        <a href="ai.php"><i class='bx bx-bot'></i>Astro AI</a>
        <a href="flashcards.php"><i class='bx bx-collection'></i>Flashcards</a>
        <a href="settings.php"><i class='bx bx-cog'></i>Settings</a>
      </div>
    </div>
  </div>

  <!-- HEADING -->
  <div class="page-heading">
    <h1>Quiz</h1>
    <p><?= count($decks) ?> quiz<?= count($decks)!=1?'zes':'' ?> · <?= count($docs) ?> document<?= count($docs)!=1?'s':'' ?></p>
  </div>

  <!-- MAIN STAGE -->
  <div class="main-stage">

    <!-- Generate CTA -->
    <div class="section">
      <button class="gen-btn-card" onclick="openGenModal()">
        <i class="fas fa-brain" style="font-size:36px;color:var(--blue)"></i>
        <div class="gen-btn-title">Generate Quiz with Astro</div>
        <div class="gen-btn-sub">AI-powered questions from any topic or document</div>
      </button>
    </div>

    <!-- Your Quizzes -->
    <div class="section">
      <div class="section-header">
        <div class="section-title"><i class='fas fa-list-check'></i>Your Quizzes</div>
        <span class="section-link"><?= count($decks) ?> total</span>
      </div>
      <div class="h-scroll" id="decks-row">
        <?php if (empty($decks)): ?>
          <div class="deck-card-add" onclick="openGenModal()">
            <i class='bx bx-plus'></i><span>Generate your first quiz</span>
          </div>
        <?php else: ?>
          <?php foreach ($decks as $d): ?>
          <div class="deck-card" id="dk-<?= $d['id'] ?>" onclick="startQuiz(<?= $d['id'] ?>)">
            <div class="deck-card-top">
              <div class="deck-icon-wrap">
                <i class="fas fa-question-circle" style="color:<?= typeColor($d['quiz_type']) ?>"></i>
              </div>
              <span class="deck-tag" style="background:<?= diffBg($d['difficulty']) ?>;color:<?= diffColor($d['difficulty']) ?>"><?= e($d['difficulty']) ?></span>
            </div>
            <div class="deck-nums">
              <span class="big"><?= (int)$d['question_count'] ?></span>
              <span class="slash">&nbsp;Q</span>
            </div>
            <div class="deck-sub-lbl"><?= $d['is_timed'] ? '⏱ '.(int)$d['seconds_per_question'].'s each' : 'Untimed' ?></div>
            <div class="deck-title-txt"><?= e($d['title']) ?></div>
            <button class="deck-del" onclick="event.stopPropagation();deleteDeck(<?= $d['id'] ?>,'dk-<?= $d['id'] ?>')">
              <i class='bx bx-trash'></i>
            </button>
          </div>
          <?php endforeach; ?>
          <div class="deck-card-add" onclick="openGenModal()">
            <i class='bx bx-plus'></i><span>New Quiz</span>
          </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- Documents -->
    <div class="section">
      <div class="section-header">
        <div class="section-title"><i class='fas fa-folder-open'></i>Documents</div>
        <span class="section-link">tap to generate</span>
      </div>
      <div class="h-scroll" id="docs-row">
        <label class="doc-upload-card">
          <i class='bx bx-cloud-upload'></i>
          <span>UPLOAD<br>PDF, DOCX, TXT<br>max 5MB</span>
          <input type="file" id="doc-file-input" accept=".pdf,.txt,.docx,.doc,.html,.csv,.md" style="display:none" onchange="handleDocUpload(this)">
        </label>
        <?php foreach ($docs as $doc):
          $color = getFileColor($doc['original_name']);
          $ext   = strtoupper(pathinfo($doc['original_name'], PATHINFO_EXTENSION));
        ?>
          <div class="doc-card" onclick="openDocModal(<?= $doc['id'] ?>,'<?= e(addslashes($doc['original_name'])) ?>','<?= $color ?>','<?= $ext ?>')">
            <div class="doc-file-icon" style="background:<?= $color ?>"><?= $ext ?></div>
            <div class="doc-card-name"><?= e($doc['original_name']) ?></div>
          </div>
        <?php endforeach; ?>
      </div>
    </div>

  </div><!-- /main-stage -->
</div><!-- /shell -->

<!-- ════════════════════════════════════════
     GENERATE QUIZ MODAL
════════════════════════════════════════ -->
<div class="modal-backdrop" id="gen-modal" onclick="if(event.target===this)closeModal('gen-modal')">
  <div class="modal-sheet" onclick="event.stopPropagation()">
    <div class="modal-handle"></div>
    <div class="modal-title">✨ Generate Quiz</div>
    <div class="modal-body">
      <label class="modal-label">Topic / Subject *</label>
      <input type="text" class="modal-input" id="gen-topic" placeholder="e.g. World War II, Photosynthesis...">

      <label class="modal-label">Number of Questions</label>
      <div class="count-row" id="gen-count-row">
        <button class="count-btn" data-n="3" onclick="pickCount('gen',this,3)">3</button>
        <button class="count-btn on" data-n="5" onclick="pickCount('gen',this,5)">5</button>
        <button class="count-btn" data-n="7" onclick="pickCount('gen',this,7)">7</button>
        <button class="count-btn" data-n="10" onclick="pickCount('gen',this,10)">10</button>
      </div>

      <label class="modal-label">Question Type</label>
      <div class="tog-row" id="gen-type-row">
        <button class="tog-btn on" data-t="multiple_choice" onclick="pickType('gen',this,'multiple_choice')"><i class='fas fa-list-ul'></i>MCQ</button>
        <button class="tog-btn" data-t="identification" onclick="pickType('gen',this,'identification')"><i class='fas fa-keyboard'></i>ID</button>
        <button class="tog-btn" data-t="true_false" onclick="pickType('gen',this,'true_false')"><i class='fas fa-check-double'></i>T/F</button>
        <button class="tog-btn" data-t="short_answer" onclick="pickType('gen',this,'short_answer')"><i class='fas fa-pen'></i>Short</button>
        <button class="tog-btn" data-t="all" onclick="pickType('gen',this,'all')"><i class='fas fa-shapes'></i>Mixed</button>
      </div>

      <label class="modal-label">Difficulty</label>
      <div class="tog-row" id="gen-diff-row">
        <button class="tog-btn" data-d="easy" onclick="pickDiff('gen',this,'easy')"><i class='fas fa-leaf'></i>Easy</button>
        <button class="tog-btn on" data-d="medium" onclick="pickDiff('gen',this,'medium')"><i class='fas fa-flame'></i>Medium</button>
        <button class="tog-btn" data-d="hard" onclick="pickDiff('gen',this,'hard')"><i class='fas fa-bolt'></i>Hard</button>
      </div>

      <label class="modal-label">Timer per question</label>
      <div class="timer-row">
        <span class="timer-lbl">Enable countdown timer</span>
        <button class="sw" id="gen-timer-sw" onclick="toggleSw('gen')"><div class="sw-knob"></div></button>
      </div>
      <div class="tog-row" id="gen-secs-row" style="display:none;margin-top:8px">
        <button class="tog-btn" data-s="15" onclick="pickSecs('gen',this,15)">15s</button>
        <button class="tog-btn on" data-s="30" onclick="pickSecs('gen',this,30)">30s</button>
        <button class="tog-btn" data-s="45" onclick="pickSecs('gen',this,45)">45s</button>
        <button class="tog-btn" data-s="60" onclick="pickSecs('gen',this,60)">60s</button>
      </div>
      <div id="gen-err" style="color:#dc2626;font-size:12px;margin-top:4px;display:none;"></div>
    </div>
    <div class="modal-footer">
      <button class="modal-btn" onclick="closeModal('gen-modal')">Cancel</button>
      <button class="modal-btn primary" onclick="submitGen()"><i class='fas fa-bolt'></i>Generate</button>
    </div>
  </div>
</div>

<!-- ════════════════════════════════════════
     DOCUMENT MODAL
════════════════════════════════════════ -->
<div class="modal-backdrop" id="doc-modal" onclick="if(event.target===this)closeModal('doc-modal')">
  <div class="modal-sheet" onclick="event.stopPropagation()">
    <div class="modal-handle"></div>
    <div class="modal-title">📄 Generate from Document</div>
    <div class="modal-body">
      <div class="doc-sel-row">
        <div class="doc-sel-icon" id="dm-icon"></div>
        <div style="flex:1;overflow:hidden">
          <div class="doc-sel-name" id="dm-name">filename.pdf</div>
          <div class="doc-sel-sub">Document selected</div>
        </div>
      </div>

      <label class="modal-label">Number of Questions</label>
      <div class="count-row" id="dm-count-row">
        <button class="count-btn" data-n="3" onclick="pickCount('dm',this,3)">3</button>
        <button class="count-btn on" data-n="5" onclick="pickCount('dm',this,5)">5</button>
        <button class="count-btn" data-n="7" onclick="pickCount('dm',this,7)">7</button>
        <button class="count-btn" data-n="10" onclick="pickCount('dm',this,10)">10</button>
      </div>

      <label class="modal-label">Question Type</label>
      <div class="tog-row" id="dm-type-row">
        <button class="tog-btn on" data-t="multiple_choice" onclick="pickType('dm',this,'multiple_choice')"><i class='fas fa-list-ul'></i>MCQ</button>
        <button class="tog-btn" data-t="identification" onclick="pickType('dm',this,'identification')"><i class='fas fa-keyboard'></i>ID</button>
        <button class="tog-btn" data-t="true_false" onclick="pickType('dm',this,'true_false')"><i class='fas fa-check-double'></i>T/F</button>
        <button class="tog-btn" data-t="short_answer" onclick="pickType('dm',this,'short_answer')"><i class='fas fa-pen'></i>Short</button>
        <button class="tog-btn" data-t="all" onclick="pickType('dm',this,'all')"><i class='fas fa-shapes'></i>Mixed</button>
      </div>

      <label class="modal-label">Difficulty</label>
      <div class="tog-row" id="dm-diff-row">
        <button class="tog-btn" data-d="easy" onclick="pickDiff('dm',this,'easy')"><i class='fas fa-leaf'></i>Easy</button>
        <button class="tog-btn on" data-d="medium" onclick="pickDiff('dm',this,'medium')"><i class='fas fa-flame'></i>Medium</button>
        <button class="tog-btn" data-d="hard" onclick="pickDiff('dm',this,'hard')"><i class='fas fa-bolt'></i>Hard</button>
      </div>

      <label class="modal-label">Timer per question</label>
      <div class="timer-row">
        <span class="timer-lbl">Enable countdown timer</span>
        <button class="sw" id="dm-timer-sw" onclick="toggleSw('dm')"><div class="sw-knob"></div></button>
      </div>
      <div class="tog-row" id="dm-secs-row" style="display:none;margin-top:8px">
        <button class="tog-btn" data-s="15" onclick="pickSecs('dm',this,15)">15s</button>
        <button class="tog-btn on" data-s="30" onclick="pickSecs('dm',this,30)">30s</button>
        <button class="tog-btn" data-s="45" onclick="pickSecs('dm',this,45)">45s</button>
        <button class="tog-btn" data-s="60" onclick="pickSecs('dm',this,60)">60s</button>
      </div>
      <div id="dm-err" style="color:#dc2626;font-size:12px;margin-top:4px;display:none;"></div>
    </div>
    <div class="modal-footer">
      <button class="modal-btn" onclick="closeModal('doc-modal')">Cancel</button>
      <button class="modal-btn primary" onclick="submitDocModal()"><i class='fas fa-bolt'></i>Generate</button>
    </div>
  </div>
</div>

<!-- ════════════════════════════════════════
     SPINNER MODAL
════════════════════════════════════════ -->
<div class="modal-backdrop" id="spin-modal">
  <div class="modal-sheet">
    <div class="modal-handle"></div>
    <div class="gen-spinner">
      <i class="fas fa-brain" style="font-size:48px;color:var(--blue)"></i>
      <p>Generating quiz…</p>
      <small id="spin-sub">Astro is crafting questions</small>
      <div class="spin-dots">
        <div class="spin-dot"></div><div class="spin-dot"></div><div class="spin-dot"></div>
      </div>
    </div>
  </div>
</div>

<!-- ════════════════════════════════════════
     STUDY OVERLAY
════════════════════════════════════════ -->
<div class="study-overlay" id="study-overlay">

  <div class="study-topbar">
    <button class="icon-btn" onclick="closeStudy()"><i class='bx bx-x'></i></button>
    <div class="study-info">
      <h2 id="study-title">Quiz</h2>
      <p id="study-counter">Question 1 of 5</p>
    </div>
    <div class="prog-ring-wrap" id="timer-ring-wrap" style="display:none">
      <svg width="38" height="38" viewBox="0 0 38 38">
        <circle class="prog-ring-bg" cx="19" cy="19" r="16"/>
        <circle class="prog-ring-fill" id="timer-ring" cx="19" cy="19" r="16"
                stroke-dasharray="100.53" stroke-dashoffset="0" stroke="#ef4444"/>
      </svg>
    </div>
    <div class="icon-btn" id="score-chip" style="display:none;font-size:11px;font-weight:700;color:var(--green)"></div>
  </div>

  <div class="study-progress"><div class="study-progress-fill" id="study-prog" style="width:0%"></div></div>
  <div class="study-timer hidden" id="study-timer">30</div>

  <div class="study-stage" id="study-stage">
    <!-- Filled by JS -->
  </div>

  <div class="study-controls hidden" id="study-controls">
    <button class="study-btn miss" onclick="skipQuestion()"><i class='bx bx-x-circle'></i>Skip</button>
    <button class="study-btn got"  onclick="nextQuestion()"><i class='bx bx-right-arrow-circle'></i>Next</button>
  </div>

  <!-- Results -->
  <div class="results-screen" id="results-screen">
    <div class="results-emoji" id="res-emoji">🎉</div>
    <div class="results-score" id="res-score">0%</div>
    <div class="results-msg" id="res-msg">Keep going!</div>
    <div class="results-grid">
      <div class="res-stat"><div class="res-stat-val" id="res-correct">0</div><div class="res-stat-lbl">Correct</div></div>
      <div class="res-stat"><div class="res-stat-val" id="res-wrong">0</div><div class="res-stat-lbl">Wrong</div></div>
      <div class="res-stat"><div class="res-stat-val" id="res-time">0s</div><div class="res-stat-lbl">Time</div></div>
    </div>
    <div class="results-btns">
      <button class="modal-btn" onclick="retryQuiz()"><i class='bx bx-revision'></i>Retry</button>
      <button class="modal-btn primary" onclick="closeStudy()"><i class='bx bx-arrow-back'></i>Back</button>
    </div>
  </div>

</div>

<div class="toast-wrap" id="toast-wrap"></div>

<script>
// ══════════════════════════════════════════════════════════
// CONSTANTS
// ══════════════════════════════════════════════════════════
const CSRF = document.querySelector('meta[name="csrf-token"]').content;

// ── State buckets for each modal ──────────────────────────
const S = {
  gen: { count:5, diff:'medium', type:'multiple_choice', timed:false, secs:30 },
  dm:  { count:5, diff:'medium', type:'multiple_choice', timed:false, secs:30 },
};
let activeDocId=0, activeDocName='', activeDocColor='', activeDocExt='';

// ── Quiz session state ────────────────────────────────────
let Q = {
  deck: null,
  questions: [],
  idx: 0,
  attemptId: null,
  correct: 0,
  wrong: 0,
  totalTime: 0,
  qStart: 0,
  timerInt: null,
  timeLeft: 0,
  awaitingNext: false,   // true after feedback shown, waiting for "Next"
  lastAnswerCorrect: false,
};

// ══════════════════════════════════════════════════════════
// TOAST
// ══════════════════════════════════════════════════════════
function toast(msg, type='', dur=2600){
  const wrap = document.getElementById('toast-wrap');
  const el   = document.createElement('div');
  el.className = 'toast ' + type;
  el.textContent = msg;
  wrap.appendChild(el);
  setTimeout(()=>{ el.style.transition='opacity .3s'; el.style.opacity=0; setTimeout(()=>el.remove(),300); }, dur);
}

// ══════════════════════════════════════════════════════════
// MODAL OPEN / CLOSE
// ══════════════════════════════════════════════════════════
function openModal(id){  document.getElementById(id).classList.add('open'); }
function closeModal(id){ document.getElementById(id).classList.remove('open'); }

function openGenModal(){
  document.getElementById('gen-err').style.display = 'none';
  document.getElementById('gen-topic').value = '';
  openModal('gen-modal');
  setTimeout(()=>document.getElementById('gen-topic').focus(), 350);
}

// ══════════════════════════════════════════════════════════
// PICKER HELPERS — work for both modals ('gen' | 'dm')
// ══════════════════════════════════════════════════════════
function pickCount(ns, btn, n){
  document.querySelectorAll(`#${ns}-count-row .count-btn`).forEach(b=>b.classList.remove('on'));
  btn.classList.add('on');
  S[ns].count = n;
}
function pickType(ns, btn, t){
  document.querySelectorAll(`#${ns}-type-row .tog-btn`).forEach(b=>b.classList.remove('on'));
  btn.classList.add('on');
  S[ns].type = t;
}
function pickDiff(ns, btn, d){
  document.querySelectorAll(`#${ns}-diff-row .tog-btn`).forEach(b=>b.classList.remove('on'));
  btn.classList.add('on');
  S[ns].diff = d;
}
function pickSecs(ns, btn, s){
  document.querySelectorAll(`#${ns}-secs-row .tog-btn`).forEach(b=>b.classList.remove('on'));
  btn.classList.add('on');
  S[ns].secs = s;
}
function toggleSw(ns){
  const sw = document.getElementById(ns + '-timer-sw');
  sw.classList.toggle('on');
  S[ns].timed = sw.classList.contains('on');
  document.getElementById(ns + '-secs-row').style.display = S[ns].timed ? 'flex' : 'none';
}

// ══════════════════════════════════════════════════════════
// SUBMIT GENERATE (topic)
// ══════════════════════════════════════════════════════════
function submitGen(){
  const topic = document.getElementById('gen-topic').value.trim();
  const errEl = document.getElementById('gen-err');
  if (!topic){ errEl.textContent='Please enter a topic.'; errEl.style.display='block'; return; }
  errEl.style.display='none';
  closeModal('gen-modal');
  runGenerate({ topic, count:S.gen.count, difficulty:S.gen.diff, quiz_type:S.gen.type, is_timed:S.gen.timed, seconds_per_question:S.gen.secs });
}

// ══════════════════════════════════════════════════════════
// DOC MODAL
// ══════════════════════════════════════════════════════════
function openDocModal(id, name, color, ext){
  activeDocId    = id;
  activeDocName  = name;
  activeDocColor = color;
  activeDocExt   = ext;
  document.getElementById('dm-icon').style.background = color;
  document.getElementById('dm-icon').textContent = ext;
  document.getElementById('dm-name').textContent = name;
  document.getElementById('dm-err').style.display = 'none';
  // Reset timer switch
  const sw = document.getElementById('dm-timer-sw');
  sw.classList.remove('on');
  S.dm.timed = false;
  document.getElementById('dm-secs-row').style.display = 'none';
  openModal('doc-modal');
}
function submitDocModal(){
  closeModal('doc-modal');
  runGenerate({ doc_id:activeDocId, topic:activeDocName, count:S.dm.count, difficulty:S.dm.diff, quiz_type:S.dm.type, is_timed:S.dm.timed, seconds_per_question:S.dm.secs });
}

// ══════════════════════════════════════════════════════════
// GENERATE → API CALL
// ══════════════════════════════════════════════════════════
async function runGenerate(payload){
  const msgs = ['Planning questions…','Writing items…','Checking difficulty…','Finalizing…'];
  let mi = 0;
  const spinSub = document.getElementById('spin-sub');
  const spinInt = setInterval(()=>{ spinSub.textContent = msgs[mi++ % msgs.length]; }, 1600);
  openModal('spin-modal');

  try {
    const res  = await fetch('api/quiz.php?action=generate_quiz', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ ...payload, csrf_token: CSRF }),
    });
    const data = await res.json();
    clearInterval(spinInt);
    closeModal('spin-modal');

    if (data.success) {
      toast('🎉 ' + data.count + ' questions created!', 'good', 3000);
      addDeckToRow({
        id: data.deck_id, title: data.title || payload.topic,
        difficulty: payload.difficulty, question_count: data.count,
        quiz_type: payload.quiz_type, is_timed: payload.is_timed,
        seconds_per_question: payload.seconds_per_question,
      });
    } else {
      toast(data.message || 'Generation failed', 'bad', 4000);
    }
  } catch(e) {
    clearInterval(spinInt);
    closeModal('spin-modal');
    toast('Network error. Try again.', 'bad');
  }
}

function addDeckToRow(d){
  const diffColors={easy:'#22c55e',medium:'#f59e0b',hard:'#ef4444'};
  const diffBgs={easy:'#d1fae5',medium:'#fef3c7',hard:'#fee2e2'};
  const typeC={multiple_choice:'#3b82f6',identification:'#8b5cf6',true_false:'#f59e0b',short_answer:'#ec4899',all:'#6366f1'};
  const dc=diffColors[d.difficulty]||'#888'; const db=diffBgs[d.difficulty]||'#f3f4f6';
  const tc=typeC[d.quiz_type]||'#6b7280';
  const row  = document.getElementById('decks-row');
  const add  = row.querySelector('.deck-card-add');
  const div  = document.createElement('div');
  div.className = 'deck-card';
  div.id = 'dk-'+d.id;
  div.onclick = () => startQuiz(d.id);
  div.innerHTML = `
    <div class="deck-card-top">
      <div class="deck-icon-wrap"><i class="fas fa-question-circle" style="color:${tc}"></i></div>
      <span class="deck-tag" style="background:${db};color:${dc}">${d.difficulty}</span>
    </div>
    <div class="deck-nums"><span class="big">${d.question_count}</span><span class="slash">&nbsp;Q</span></div>
    <div class="deck-sub-lbl">${d.is_timed?'⏱ '+d.seconds_per_question+'s each':'Untimed'}</div>
    <div class="deck-title-txt">${esc(d.title)}</div>
    <button class="deck-del" onclick="event.stopPropagation();deleteDeck(${d.id},'dk-${d.id}')"><i class='bx bx-trash'></i></button>
  `;
  if (add) row.insertBefore(div, add); else row.appendChild(div);
  // Scroll to new card
  setTimeout(() => div.scrollIntoView({ behavior:'smooth', inline:'start' }), 100);
}

// ══════════════════════════════════════════════════════════
// DOCUMENT UPLOAD
// ══════════════════════════════════════════════════════════
async function handleDocUpload(input){
  const file = input.files[0];
  if (!file) return;
  const fd = new FormData();
  fd.append('document', file);
  fd.append('csrf_token', CSRF);
  toast('Uploading ' + file.name + '…');
  try {
    const res  = await fetch('api/ai.php?action=upload_doc', { method:'POST', body:fd });
    const data = await res.json();
    if (data.success) {
      toast('📄 ' + file.name + ' uploaded!', 'good');
      const color = getFileColor(file.name);
      const ext   = file.name.split('.').pop().toUpperCase();
      const row   = document.getElementById('docs-row');
      const el    = document.createElement('div');
      el.className = 'doc-card';
      el.onclick = () => openDocModal(data.doc_id, file.name, color, ext);
      el.innerHTML = `<div class="doc-file-icon" style="background:${color}">${ext}</div><div class="doc-card-name">${esc(file.name)}</div>`;
      row.insertBefore(el, row.children[1]);
    } else {
      toast(data.message || 'Upload failed', 'bad');
    }
  } catch(e) { toast('Upload error', 'bad'); }
  input.value = '';
}
function getFileColor(name){
  const m={pdf:'#ef4444',docx:'#2563eb',doc:'#2563eb',xlsx:'#16a34a',xls:'#16a34a',pptx:'#ea580c',ppt:'#ea580c',txt:'#6b7280',md:'#6b7280',csv:'#0891b2'};
  return m[name.split('.').pop().toLowerCase()]||'#9333ea';
}

// ══════════════════════════════════════════════════════════
// DELETE DECK
// ══════════════════════════════════════════════════════════
async function deleteDeck(id, elId){
  if (!confirm('Delete this quiz? This cannot be undone.')) return;
  try {
    const res  = await fetch('api/quiz.php?action=delete_deck', { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({deck_id:id,csrf_token:CSRF}) });
    const data = await res.json();
    if (data.success) { document.getElementById(elId)?.remove(); toast('Quiz deleted'); }
    else toast(data.message||'Failed', 'bad');
  } catch(e) { toast('Error', 'bad'); }
}

// ══════════════════════════════════════════════════════════
// START QUIZ
// ══════════════════════════════════════════════════════════
async function startQuiz(deckId){
  try {
    // 1. Start attempt
    const aRes  = await fetch('api/quiz.php?action=start_attempt', { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({deck_id:deckId,csrf_token:CSRF}) });
    const aData = await aRes.json();
    if (!aData.success) throw new Error(aData.message || 'Could not start quiz');

    // 2. Load questions
    const qRes  = await fetch('api/quiz.php?action=get_quiz&deck_id='+deckId);
    const qData = await qRes.json();
    if (!qData.success || !qData.questions.length) throw new Error('No questions found in this quiz');

    Q.deck      = aData.deck;
    Q.questions = qData.questions;
    Q.attemptId = aData.attempt_id;
    Q.idx       = 0;
    Q.correct   = 0;
    Q.wrong     = 0;
    Q.totalTime = 0;
    Q.awaitingNext = false;

    // Show/hide timer ring based on deck setting
    document.getElementById('timer-ring-wrap').style.display = Q.deck.is_timed ? 'block' : 'none';
    document.getElementById('study-timer').classList.toggle('hidden', !Q.deck.is_timed);
    document.getElementById('score-chip').style.display = 'flex';

    document.getElementById('study-overlay').classList.add('open');
    document.getElementById('results-screen').classList.remove('open');
    showQuestion();
  } catch(e) {
    toast(e.message, 'bad');
  }
}

// ══════════════════════════════════════════════════════════
// SHOW QUESTION
// ══════════════════════════════════════════════════════════
function showQuestion(){
  if (Q.idx >= Q.questions.length) { finishQuiz(); return; }

  const q        = Q.questions[Q.idx];
  const total    = Q.questions.length;
  Q.qStart       = Date.now();
  Q.awaitingNext = false;

  document.getElementById('study-title').textContent   = Q.deck.title;
  document.getElementById('study-counter').textContent = `Question ${Q.idx+1} of ${total}`;
  document.getElementById('study-prog').style.width    = (Q.idx/total*100)+'%';
  document.getElementById('score-chip').textContent    = Q.correct+'✓';
  document.getElementById('study-controls').classList.add('hidden');

  const typeColors = { multiple_choice:'#3b82f6', identification:'#8b5cf6', true_false:'#f59e0b', short_answer:'#ec4899' };
  const typeBgs    = { multiple_choice:'#dbeafe', identification:'#ede9fe', true_false:'#fef3c7', short_answer:'#fce7f3' };
  const typeLabels = { multiple_choice:'Multiple Choice', identification:'Identification', true_false:'True / False', short_answer:'Short Answer' };

  const stage = document.getElementById('study-stage');
  // Remove old feedback
  stage.querySelectorAll('.feedback-card').forEach(el=>el.remove());

  // Build question card HTML
  let optionsHTML = '';
  if ((q.question_type === 'multiple_choice' || q.question_type === 'true_false') && Array.isArray(q.options)) {
    optionsHTML = `<div class="options-list" id="opt-list">` +
      q.options.map((opt,i) =>
        `<button class="option-btn" id="opt-${i}" onclick="selectOption(${i},'${esc(opt)}')">
           <div class="opt-circle" id="oc-${i}">${String.fromCharCode(65+i)}</div>
           <span>${esc(opt)}</span>
         </button>`
      ).join('') +
    `</div>`;
  } else {
    optionsHTML = `
      <input type="text" class="answer-input" id="ans-input" placeholder="Type your answer…" autocomplete="off" onkeydown="if(event.key==='Enter')submitTextAnswer()">
      <button class="submit-ans-btn" id="submit-btn" onclick="submitTextAnswer()">
        <i class='bx bx-send'></i> Submit Answer
      </button>`;
  }

  stage.innerHTML = `
    <div class="question-card" id="q-card">
      <span class="q-type-badge" style="background:${typeBgs[q.question_type]||'#f3f4f6'};color:${typeColors[q.question_type]||'#888'}">${typeLabels[q.question_type]||q.question_type}</span>
      <div class="q-text">${esc(q.question)}</div>
      ${optionsHTML}
    </div>
  `;

  // Auto focus text input
  if (q.question_type !== 'multiple_choice' && q.question_type !== 'true_false') {
    setTimeout(()=>document.getElementById('ans-input')?.focus(), 200);
  }

  // Start countdown timer if enabled
  if (Q.deck.is_timed) startTimer(parseInt(Q.deck.seconds_per_question));
}

// ══════════════════════════════════════════════════════════
// OPTION SELECTION (MCQ / T/F — auto-submits)
// ══════════════════════════════════════════════════════════
function selectOption(idx, opt){
  if (Q.awaitingNext) return;
  // Highlight selected
  document.querySelectorAll('.option-btn').forEach(b => b.classList.remove('selected'));
  const btn = document.getElementById('opt-'+idx);
  if (btn) btn.classList.add('selected');
  // Auto-submit after brief delay
  setTimeout(() => submitAnswer(opt), 350);
}

// ══════════════════════════════════════════════════════════
// TEXT ANSWER SUBMIT (identification / short_answer)
// ══════════════════════════════════════════════════════════
function submitTextAnswer(){
  if (Q.awaitingNext) return;
  const val = document.getElementById('ans-input')?.value.trim() || '';
  submitAnswer(val);
}

// ══════════════════════════════════════════════════════════
// SUBMIT ANSWER → API
// ══════════════════════════════════════════════════════════
async function submitAnswer(userAnswer = ''){
  if (Q.awaitingNext) return;
  Q.awaitingNext = true;
  clearInterval(Q.timerInt);

  const q         = Q.questions[Q.idx];
  const timeTaken = Math.max(1, Math.floor((Date.now() - Q.qStart) / 1000));

  // Disable input while waiting
  const submitBtn = document.getElementById('submit-btn');
  if (submitBtn) submitBtn.disabled = true;

  try {
    const res  = await fetch('api/quiz.php?action=submit_answer', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        attempt_id: Q.attemptId,
        question_id: q.id,
        user_answer: userAnswer,
        time_taken: timeTaken,
        csrf_token: CSRF,
      }),
    });
    const data = await res.json();

    if (data.success) {
      Q.totalTime += timeTaken;
      if (data.is_correct) Q.correct++; else Q.wrong++;
      showFeedback(data.is_correct, q.correct_answer, q.explanation, userAnswer, q.question_type, q.options);
    } else {
      toast(data.message || 'Error submitting answer', 'bad');
      Q.awaitingNext = false;
      showControls();
    }
  } catch(e) {
    toast('Network error', 'bad');
    Q.awaitingNext = false;
    showControls();
  }
}

// ══════════════════════════════════════════════════════════
// FEEDBACK
// ══════════════════════════════════════════════════════════
function showFeedback(isCorrect, correctAnswer, explanation, userAnswer, qType, options){
  // Color the options for MCQ / T/F
  if (qType === 'multiple_choice' || qType === 'true_false') {
    document.querySelectorAll('.option-btn').forEach((btn, i) => {
      const optText = options && options[i] ? options[i] : '';
      const correct = optText.toLowerCase() === correctAnswer.toLowerCase();
      const chosen  = btn.classList.contains('selected');
      if (correct) btn.classList.add('correct');
      else if (chosen && !correct) btn.classList.add('wrong');
    });
  }

  const stage = document.getElementById('study-stage');
  const fb    = document.createElement('div');
  fb.className = 'feedback-card';
  fb.innerHTML = `
    <div class="fb-icon">${isCorrect ? '✅' : '❌'}</div>
    <div class="fb-title">${isCorrect ? 'Correct!' : 'Incorrect'}</div>
    <div class="fb-answer">
      ${!isCorrect ? `<strong>Correct answer:</strong> ${esc(correctAnswer)}<br>` : ''}
      ${userAnswer && !isCorrect ? `<span style="color:#bbb">Your answer: ${esc(userAnswer)}</span>` : ''}
    </div>
    ${explanation ? `<div class="fb-expl"><strong>Explanation</strong>${esc(explanation)}</div>` : ''}
    <button class="fb-next-btn" onclick="nextQuestion()">
      ${Q.idx + 1 >= Q.questions.length ? '🏁 Finish Quiz' : 'Next Question →'}
    </button>
  `;
  stage.appendChild(fb);
  fb.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}

function showControls(){
  document.getElementById('study-controls').classList.remove('hidden');
}

// ══════════════════════════════════════════════════════════
// NAVIGATION
// ══════════════════════════════════════════════════════════
function nextQuestion(){
  Q.idx++;
  showQuestion();
}

function skipQuestion(){
  Q.wrong++;
  Q.idx++;
  showQuestion();
}

// ══════════════════════════════════════════════════════════
// COUNTDOWN TIMER
// ══════════════════════════════════════════════════════════
function startTimer(seconds){
  clearInterval(Q.timerInt);
  Q.timeLeft = seconds;
  const timerEl = document.getElementById('study-timer');
  const ring    = document.getElementById('timer-ring');
  const circ    = 100.53;

  timerEl.textContent = seconds;
  timerEl.className   = 'study-timer';
  if (ring) ring.style.strokeDashoffset = 0;

  Q.timerInt = setInterval(() => {
    Q.timeLeft--;
    if (timerEl) {
      timerEl.textContent = Q.timeLeft;
      if (Q.timeLeft <= 5)       timerEl.className = 'study-timer danger';
      else if (Q.timeLeft <= 10) timerEl.className = 'study-timer warn';
    }
    if (ring) ring.style.strokeDashoffset = circ * (1 - Q.timeLeft / seconds);

    if (Q.timeLeft <= 0) {
      clearInterval(Q.timerInt);
      if (!Q.awaitingNext) {
        toast("Time's up!", 'bad', 2000);
        submitAnswer('');
      }
    }
  }, 1000);
}

// ══════════════════════════════════════════════════════════
// FINISH QUIZ
// ══════════════════════════════════════════════════════════
async function finishQuiz(){
  clearInterval(Q.timerInt);
  try {
    const res  = await fetch('api/quiz.php?action=complete_attempt', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ attempt_id: Q.attemptId, csrf_token: CSRF }),
    });
    const data = await res.json();
    const s    = data.success ? data.stats : { score_pct: Math.round(Q.correct/Q.questions.length*100), correct:Q.correct, wrong:Q.wrong, total_time:Q.totalTime };

    document.getElementById('res-score').textContent   = s.score_pct + '%';
    document.getElementById('res-correct').textContent = s.correct;
    document.getElementById('res-wrong').textContent   = s.wrong;
    document.getElementById('res-time').textContent    = s.total_time < 60 ? s.total_time+'s' : Math.floor(s.total_time/60)+'m '+(s.total_time%60)+'s';
    document.getElementById('res-msg').textContent     = s.score_pct>=90?'Outstanding! 🏆':s.score_pct>=75?'Great job! 🎉':s.score_pct>=60?'Good effort! 👍':'Keep practicing! 📚';
    document.getElementById('res-emoji').textContent   = s.score_pct>=90?'🏆':s.score_pct>=75?'🎉':s.score_pct>=60?'👍':'📚';
    document.getElementById('study-prog').style.width  = '100%';
    document.getElementById('results-screen').classList.add('open');
  } catch(e) {
    // Show results from local state anyway
    const pct = Q.questions.length ? Math.round(Q.correct/Q.questions.length*100) : 0;
    document.getElementById('res-score').textContent  = pct+'%';
    document.getElementById('res-correct').textContent = Q.correct;
    document.getElementById('res-wrong').textContent   = Q.wrong;
    document.getElementById('res-time').textContent    = Q.totalTime+'s';
    document.getElementById('results-screen').classList.add('open');
  }
}

function retryQuiz(){
  document.getElementById('results-screen').classList.remove('open');
  if (Q.deck) startQuiz(Q.deck.id);
}

function closeStudy(){
  clearInterval(Q.timerInt);
  document.getElementById('study-overlay').classList.remove('open');
  document.getElementById('results-screen').classList.remove('open');
  Q = { deck:null, questions:[], idx:0, attemptId:null, correct:0, wrong:0, totalTime:0, qStart:0, timerInt:null, timeLeft:0, awaitingNext:false };
}

// ══════════════════════════════════════════════════════════
// KEBAB MENU
// ══════════════════════════════════════════════════════════
document.getElementById('kebab-btn').addEventListener('click', e=>{
  e.stopPropagation();
  document.getElementById('kebab-menu').classList.toggle('open');
});
document.addEventListener('click', ()=>document.getElementById('kebab-menu').classList.remove('open'));

// ══════════════════════════════════════════════════════════
// UTILITY
// ══════════════════════════════════════════════════════════
function esc(s){ return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;'); }

// Escape key closes overlays
document.addEventListener('keydown', e=>{
  if (e.key==='Escape'){
    if (document.getElementById('study-overlay').classList.contains('open')) closeStudy();
    else ['gen-modal','doc-modal'].forEach(id=>closeModal(id));
  }
});
</script>
</body>
</html>