<?php
require_once 'includes/config.php';
requireLogin();
$uid = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
    $action = $_POST['action'] ?? '';

    if ($action === 'add_note') {
        $title   = sanitize($_POST['title'] ?? '');
        $content = $_POST['content'] ?? '';
        $subId   = (int)($_POST['subject_id'] ?? 0) ?: null;
        $color   = sanitize($_POST['color'] ?? '#6366f1');
        if (!$title) jsonResponse(['success'=>false,'message'=>'Please enter a title.']);
        $pdo->prepare("INSERT INTO notes (user_id,subject_id,title,content,color) VALUES (?,?,?,?,?)")->execute([$uid,$subId,$title,$content,$color]);
        jsonResponse(['success'=>true,'message'=>'Note saved!']);
    }
    if ($action === 'get_note') {
        $id = (int)($_POST['id'] ?? 0);
        $stmt = $pdo->prepare("SELECT * FROM notes WHERE id=? AND user_id=?");
        $stmt->execute([$id,$uid]); $row = $stmt->fetch();
        jsonResponse($row ?: ['error'=>'Not found']);
    }
    if ($action === 'delete_note') {
        $id = (int)($_POST['id'] ?? 0);
        $pdo->prepare("DELETE FROM notes WHERE id=? AND user_id=?")->execute([$id,$uid]);
        jsonResponse(['success'=>true]);
    }
    if ($action === 'pin_note') {
        $id = (int)($_POST['id'] ?? 0);
        $pdo->prepare("UPDATE notes SET is_pinned=NOT is_pinned WHERE id=? AND user_id=?")->execute([$id,$uid]);
        jsonResponse(['success'=>true]);
    }
    if ($action === 'add_flash') {
        $deck  = sanitize($_POST['deck'] ?? 'General');
        $q     = sanitize($_POST['question'] ?? '');
        $a     = sanitize($_POST['answer'] ?? '');
        $subId = (int)($_POST['subject_id'] ?? 0) ?: null;
        $diff  = sanitize($_POST['difficulty'] ?? 'medium');
        if (!$q || !$a) jsonResponse(['success'=>false,'message'=>'Question and answer are required.']);
        $pdo->prepare("INSERT INTO flashcards (user_id,subject_id,deck_name,question,answer,difficulty) VALUES (?,?,?,?,?,?)")->execute([$uid,$subId,$deck,$q,$a,$diff]);
        jsonResponse(['success'=>true,'message'=>'Flashcard added!']);
    }
    if ($action === 'delete_flash') {
        $id = (int)($_POST['id'] ?? 0);
        $pdo->prepare("DELETE FROM flashcards WHERE id=? AND user_id=?")->execute([$id,$uid]);
        jsonResponse(['success'=>true]);
    }
    if ($action === 'review_flash') {
        $id = (int)($_POST['id'] ?? 0);
        $pdo->prepare("UPDATE flashcards SET times_reviewed=times_reviewed+1, last_reviewed=NOW() WHERE id=? AND user_id=?")->execute([$id,$uid]);
        jsonResponse(['success'=>true]);
    }
}

$subjects = $pdo->prepare("SELECT id,name,color FROM subjects WHERE user_id=? ORDER BY name");
$subjects->execute([$uid]); $subjects = $subjects->fetchAll();

$notes = $pdo->prepare("SELECT n.*, s.name as subject_name, s.color as subject_color FROM notes n LEFT JOIN subjects s ON n.subject_id=s.id WHERE n.user_id=? ORDER BY n.is_pinned DESC, n.updated_at DESC");
$notes->execute([$uid]); $notes = $notes->fetchAll();

$flashcards = $pdo->prepare("SELECT f.*, s.name as subject_name FROM flashcards f LEFT JOIN subjects s ON f.subject_id=s.id WHERE f.user_id=? ORDER BY f.deck_name, f.created_at DESC");
$flashcards->execute([$uid]); $flashcards = $flashcards->fetchAll();

$decks = [];
foreach ($flashcards as $fc) $decks[$fc['deck_name']][] = $fc;

// Due-for-review count (spaced repetition) — safe if columns don't exist yet
$dueFlashCount = 0;
try {
    $dueQ = $pdo->prepare("SELECT COUNT(*) FROM flashcards WHERE user_id=? AND (next_review_date IS NULL OR next_review_date <= CURDATE())");
    $dueQ->execute([$uid]);
    $dueFlashCount = (int)$dueQ->fetchColumn();
} catch (PDOException $e) { $dueFlashCount = count($flashcards); }

$pinnedNotes  = array_filter($notes, fn($n) => $n['is_pinned']);
$regularNotes = array_filter($notes, fn($n) => !$n['is_pinned']);

require_once 'includes/header.php';
renderHeader('Notes & Flashcards', 'notes');
?>

<style>
/* ── Page header ─────────────────────────────── */
.nf-page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 24px;
  flex-wrap: wrap;
}
.nf-page-title {
  font-size: 22px;
  font-weight: 800;
  color: var(--text-primary);
  font-family: 'Sora', sans-serif;
  letter-spacing: -.3px;
}
.nf-page-sub { font-size: 13px; color: var(--text-muted); margin-top: 4px; }

/* ── Tab switcher ────────────────────────────── */
.nf-tab-bar {
  display: flex;
  gap: 4px;
  background: var(--bg-secondary);
  border: 1px solid var(--border);
  border-radius: 12px;
  padding: 4px;
  margin-bottom: 22px;
}
.nf-tab-btn {
  flex: 1;
  padding: 8px 18px;
  border-radius: 9px;
  border: none;
  background: transparent;
  color: var(--text-secondary);
  font-size: 13px;
  font-weight: 600;
  cursor: pointer;
  transition: all .18s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 7px;
  white-space: nowrap;
  font-family: inherit;
}
.nf-tab-btn.active {
  background: var(--bg-card);
  color: var(--text-primary);
  box-shadow: 0 1px 4px rgba(0,0,0,.2);
}
.nf-tab-btn:hover:not(.active) { color: var(--text-primary); }
.nf-tab-count {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 18px;
  height: 18px;
  padding: 0 5px;
  border-radius: 99px;
  background: rgba(99,102,241,.15);
  color: var(--accent);
  font-size: 10px;
  font-weight: 800;
}

/* ── Section label ───────────────────────────── */
.nf-section-label {
  font-size: 11px;
  font-weight: 700;
  color: var(--text-muted);
  text-transform: uppercase;
  letter-spacing: 1px;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 8px;
}
.nf-section-label::after {
  content: '';
  flex: 1;
  height: 1px;
  background: var(--border);
}

/* ── Notes grid ──────────────────────────────── */
.notes-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(230px, 1fr));
  gap: 12px;
  margin-bottom: 24px;
}

/* ── Note card ───────────────────────────────── */
.note-card {
  background: var(--bg-card);
  border: 1px solid var(--border);
  border-radius: 14px;
  padding: 16px;
  cursor: pointer;
  transition: transform .18s, box-shadow .18s, border-color .18s;
  position: relative;
  overflow: hidden;
  animation: cardIn .25s ease both;
}
.note-card::before {
  content: '';
  position: absolute;
  top: 0; left: 0; right: 0;
  height: 3px;
  border-radius: 14px 14px 0 0;
}
.note-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(0,0,0,.15);
  border-color: rgba(99,102,241,.3);
}
@keyframes cardIn {
  from { opacity: 0; transform: translateY(8px); }
  to   { opacity: 1; transform: translateY(0); }
}
.note-card-top {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 8px;
  margin-bottom: 8px;
}
.note-card-title {
  font-size: 14px;
  font-weight: 700;
  color: var(--text-primary);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
  min-width: 0;
}
.note-card-actions {
  display: flex;
  gap: 4px;
  flex-shrink: 0;
  opacity: 0;
  transition: opacity .15s;
}
.note-card:hover .note-card-actions { opacity: 1; }
.note-action-btn {
  width: 26px; height: 26px;
  border-radius: 7px;
  border: 1px solid var(--border);
  background: var(--bg-secondary);
  color: var(--text-muted);
  cursor: pointer;
  display: flex; align-items: center; justify-content: center;
  transition: all .15s;
  font-size: 12px;
}
.note-action-btn:hover { border-color: var(--accent); color: var(--accent); background: rgba(99,102,241,.08); }
.note-action-btn.del:hover { border-color: rgba(239,68,68,.4); color: #ef4444; background: rgba(239,68,68,.08); }

.note-subject {
  display: inline-flex;
  align-items: center;
  gap: 5px;
  font-size: 11px;
  font-weight: 600;
  color: var(--text-secondary);
  background: var(--bg-secondary);
  border: 1px solid var(--border);
  border-radius: 99px;
  padding: 2px 9px;
  margin-bottom: 10px;
}
.note-subject-dot {
  width: 7px; height: 7px; border-radius: 50%; flex-shrink: 0;
}
.note-preview {
  font-size: 12.5px;
  color: var(--text-secondary);
  line-height: 1.6;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  margin-bottom: 12px;
}
.note-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 11px;
  color: var(--text-muted);
}
.note-pin-badge {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  font-size: 10px;
  font-weight: 700;
  color: #f59e0b;
  background: rgba(245,158,11,.1);
  border: 1px solid rgba(245,158,11,.2);
  border-radius: 99px;
  padding: 1px 7px;
}

/* ── Flashcard deck ──────────────────────────── */
.deck-card {
  background: var(--bg-card);
  border: 1px solid var(--border);
  border-radius: 14px;
  overflow: hidden;
  margin-bottom: 12px;
}
.deck-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 14px 18px;
  border-bottom: 1px solid var(--border);
  cursor: pointer;
  transition: background .15s;
}
.deck-header:hover { background: rgba(99,102,241,.04); }
.deck-title {
  font-size: 14px;
  font-weight: 700;
  color: var(--text-primary);
  display: flex;
  align-items: center;
  gap: 10px;
}
.deck-actions { display: flex; gap: 8px; align-items: center; }

.fc-item {
  display: flex;
  align-items: flex-start;
  gap: 14px;
  padding: 14px 18px;
  border-bottom: 1px solid var(--border);
  transition: background .15s;
}
.fc-item:last-child { border-bottom: none; }
.fc-item:hover { background: rgba(255,255,255,.02); }
.fc-content { flex: 1; min-width: 0; }
.fc-question {
  font-size: 13px;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 4px;
  line-height: 1.5;
}
.fc-answer {
  font-size: 13px;
  color: var(--text-secondary);
  line-height: 1.5;
  display: none;
  background: rgba(99,102,241,.06);
  border: 1px solid rgba(99,102,241,.15);
  border-radius: 8px;
  padding: 8px 12px;
  margin-top: 8px;
}
.fc-show-btn {
  background: none;
  border: none;
  color: var(--accent);
  font-size: 12px;
  font-weight: 600;
  cursor: pointer;
  padding: 4px 0;
  font-family: inherit;
  transition: opacity .15s;
}
.fc-show-btn:hover { opacity: .7; }
.fc-meta { display: flex; flex-direction: column; align-items: flex-end; gap: 6px; flex-shrink: 0; }
.diff-badge {
  font-size: 10px;
  font-weight: 700;
  padding: 2px 9px;
  border-radius: 99px;
  text-transform: uppercase;
  letter-spacing: .3px;
}
.diff-easy   { background: rgba(16,185,129,.12); color: #34d399; border: 1px solid rgba(16,185,129,.25); }
.diff-medium { background: rgba(245,158,11,.12); color: #fbbf24; border: 1px solid rgba(245,158,11,.25); }
.diff-hard   { background: rgba(239,68,68,.12);  color: #f87171; border: 1px solid rgba(239,68,68,.25); }

/* ── Quiz modal ──────────────────────────────── */
.quiz-card {
  background: var(--bg-secondary);
  border: 1px solid var(--border);
  border-radius: 14px;
  padding: 32px 24px;
  min-height: 130px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16px;
}
.quiz-answer-box {
  background: rgba(99,102,241,.07);
  border: 1px solid rgba(99,102,241,.2);
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 16px;
  font-size: 14px;
  color: var(--text-secondary);
  line-height: 1.6;
  display: none;
}

/* ── Color swatches ──────────────────────────── */
.color-swatches {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  margin-top: 4px;
}
.color-swatch {
  width: 28px; height: 28px;
  border-radius: 8px;
  cursor: pointer;
  border: 2px solid transparent;
  transition: transform .15s, border-color .15s;
}
.color-swatch:hover { transform: scale(1.15); }
.color-swatch.selected { border-color: var(--text-primary); transform: scale(1.1); }
</style>

<!-- Page Header -->
<div class="nf-page-header">
  <div>
    <div class="nf-page-title">📝 Notes &amp; Flashcards</div>
    <div class="nf-page-sub"><?= count($notes) ?> notes · <?= count($flashcards) ?> flashcards</div>
  </div>
  <div style="display:flex;gap:8px;flex-wrap:wrap">
  <?php if ($dueFlashCount > 0): ?>
  <a href="<?= defined('SITE_URL') ? SITE_URL : '' ?>/flashcards-review" class="btn btn-secondary">
    🔁 Review Due <span class="nf-tab-count" style="margin-left:4px"><?= $dueFlashCount ?></span>
  </a>
  <?php endif; ?>
  <button class="btn btn-primary" id="addBtn" onclick="openAddModal()">
    <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" style="margin-right:6px"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
    <span id="addBtnLabel">Add Note</span>
  </button>
  </div>
</div>

<!-- Tab Bar -->
<div class="nf-tab-bar">
  <button class="nf-tab-btn active" id="tabNotes" onclick="switchTab('notes')">
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
    Notes
    <span class="nf-tab-count"><?= count($notes) ?></span>
  </button>
  <button class="nf-tab-btn" id="tabFlash" onclick="switchTab('flash')">
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8M12 17v4"/></svg>
    Flashcards
    <span class="nf-tab-count"><?= count($flashcards) ?></span>
  </button>
</div>

<!-- NOTES TAB ──────────────────────────────────────────────────────── -->
<div id="notesTab">
  <?php if ($notes): ?>

  <?php if ($pinnedNotes): ?>
  <div class="nf-section-label">📌 Pinned</div>
  <div class="notes-grid" style="margin-bottom:20px">
    <?php foreach ($pinnedNotes as $i => $n): ?>
    <?php
      $color = htmlspecialchars($n['color'] ?? '#6366f1');
    ?>
    <div class="note-card" id="note-<?= $n['id'] ?>" style="animation-delay:<?= $i*0.04 ?>s" onclick="viewNote(<?= $n['id'] ?>)">
      <div class="note-card::before" style="background:<?= $color ?>"></div>
      <style>#note-<?= $n['id'] ?>::before { background: <?= $color ?>; }</style>
      <div class="note-card-top">
        <div class="note-card-title"><?= htmlspecialchars($n['title']) ?></div>
        <div class="note-card-actions" onclick="event.stopPropagation()">
          <button class="note-action-btn" title="Unpin" onclick="pinNote(<?= $n['id'] ?>)">
            <svg width="11" height="11" viewBox="0 0 24 24" fill="currentColor" stroke="none"><path d="M12 2l2.4 7.4H22l-6.2 4.5 2.4 7.4L12 17l-6.2 4.3 2.4-7.4L2 9.4h7.6z"/></svg>
          </button>
          <button class="note-action-btn del" title="Delete" onclick="deleteNote(<?= $n['id'] ?>)">
            <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14H6L5 6"/></svg>
          </button>
        </div>
      </div>
      <?php if ($n['subject_name']): ?>
      <div class="note-subject" style="margin-bottom:10px">
        <span class="note-subject-dot" style="background:<?= htmlspecialchars($n['subject_color'] ?? '#6366f1') ?>"></span>
        <?= htmlspecialchars($n['subject_name']) ?>
      </div>
      <?php endif; ?>
      <div class="note-preview"><?= htmlspecialchars(strip_tags($n['content'])) ?: '<em style="opacity:.4">No content</em>' ?></div>
      <div class="note-footer">
        <span class="note-pin-badge">📌 Pinned</span>
        <span><?= date('M j, Y', strtotime($n['updated_at'])) ?></span>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
  <?php endif; ?>

  <?php if ($regularNotes): ?>
  <?php if ($pinnedNotes): ?><div class="nf-section-label">All Notes</div><?php endif; ?>
  <div class="notes-grid">
    <?php foreach ($regularNotes as $i => $n): ?>
    <?php $color = htmlspecialchars($n['color'] ?? '#6366f1'); ?>
    <div class="note-card" id="note-<?= $n['id'] ?>" style="animation-delay:<?= min($i*0.04, 0.3) ?>s" onclick="viewNote(<?= $n['id'] ?>)">
      <style>#note-<?= $n['id'] ?>::before { background: <?= $color ?>; }</style>
      <div class="note-card-top">
        <div class="note-card-title"><?= htmlspecialchars($n['title']) ?></div>
        <div class="note-card-actions" onclick="event.stopPropagation()">
          <button class="note-action-btn" title="Pin" onclick="pinNote(<?= $n['id'] ?>)">
            <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M12 2l2.4 7.4H22l-6.2 4.5 2.4 7.4L12 17l-6.2 4.3 2.4-7.4L2 9.4h7.6z"/></svg>
          </button>
          <button class="note-action-btn del" title="Delete" onclick="deleteNote(<?= $n['id'] ?>)">
            <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14H6L5 6"/></svg>
          </button>
        </div>
      </div>
      <?php if ($n['subject_name']): ?>
      <div class="note-subject">
        <span class="note-subject-dot" style="background:<?= htmlspecialchars($n['subject_color'] ?? '#6366f1') ?>"></span>
        <?= htmlspecialchars($n['subject_name']) ?>
      </div>
      <?php endif; ?>
      <div class="note-preview"><?= htmlspecialchars(strip_tags($n['content'])) ?: '<em style="opacity:.4">No content</em>' ?></div>
      <div class="note-footer">
        <span style="display:flex;align-items:center;gap:4px">
          <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
          <?= date('M j, Y', strtotime($n['updated_at'])) ?>
        </span>
        <span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:<?= $color ?>"></span>
      </div>
    </div>
    <?php endforeach; ?>
  </div>
  <?php endif; ?>

  <?php else: ?>
  <div style="text-align:center;padding:64px 20px;background:var(--bg-card);border:1px dashed var(--border);border-radius:16px">
    <div style="font-size:48px;margin-bottom:14px">📝</div>
    <div style="font-size:16px;font-weight:700;color:var(--text-primary);margin-bottom:6px;font-family:'Sora',sans-serif">No notes yet</div>
    <div style="font-size:13px;color:var(--text-muted);margin-bottom:20px">Start capturing your study notes!</div>
    <button class="btn btn-primary" onclick="openAddModal()">Add your first note</button>
  </div>
  <?php endif; ?>
</div>

<!-- FLASHCARDS TAB ─────────────────────────────────────────────────── -->
<div id="flashTab" style="display:none">
  <?php if ($decks): ?>
  <?php foreach ($decks as $deckName => $cards): ?>
  <div class="deck-card">
    <div class="deck-header" onclick="toggleDeck(this)">
      <div class="deck-title">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" style="color:var(--accent)"><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8M12 17v4"/></svg>
        <?= htmlspecialchars($deckName) ?>
        <span style="font-size:11px;font-weight:700;background:rgba(99,102,241,.12);color:var(--accent);border:1px solid rgba(99,102,241,.2);border-radius:99px;padding:1px 9px"><?= count($cards) ?></span>
      </div>
      <div class="deck-actions" onclick="event.stopPropagation()">
        <button class="btn btn-primary btn-sm" onclick="startQuiz('<?= htmlspecialchars(addslashes($deckName)) ?>')">
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" style="margin-right:5px"><polygon points="5 3 19 12 5 21 5 3"/></svg>
          Quiz
        </button>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" style="color:var(--text-muted);transition:transform .2s" class="deck-chevron"><polyline points="6 9 12 15 18 9"/></svg>
      </div>
    </div>
    <div class="deck-body">
      <?php foreach ($cards as $fc): ?>
      <div class="fc-item" id="fc-<?= $fc['id'] ?>">
        <div class="fc-content">
          <div class="fc-question">Q: <?= htmlspecialchars($fc['question']) ?></div>
          <div class="fc-answer" id="fca-<?= $fc['id'] ?>">A: <?= htmlspecialchars($fc['answer']) ?></div>
          <button class="fc-show-btn" onclick="toggleAnswer(<?= $fc['id'] ?>, this)">Show Answer</button>
        </div>
        <div class="fc-meta">
          <span class="diff-badge diff-<?= $fc['difficulty'] ?>"><?= ucfirst($fc['difficulty']) ?></span>
          <span style="font-size:11px;color:var(--text-muted)"><?= $fc['times_reviewed'] ?>× reviewed</span>
          <button class="note-action-btn del" onclick="deleteFlash(<?= $fc['id'] ?>)" title="Delete">
            <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14H6L5 6"/></svg>
          </button>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
  <?php endforeach; ?>
  <?php else: ?>
  <div style="text-align:center;padding:64px 20px;background:var(--bg-card);border:1px dashed var(--border);border-radius:16px">
    <div style="font-size:48px;margin-bottom:14px">🃏</div>
    <div style="font-size:16px;font-weight:700;color:var(--text-primary);margin-bottom:6px;font-family:'Sora',sans-serif">No flashcards yet</div>
    <div style="font-size:13px;color:var(--text-muted);margin-bottom:20px">Create flashcards to test your knowledge!</div>
    <button class="btn btn-primary" onclick="switchTab('flash');openAddModal()">Add first flashcard</button>
  </div>
  <?php endif; ?>
</div>

<!-- ── Add Note Modal ──────────────────────────────────────────────── -->
<div class="modal-overlay" id="noteModal">
  <div class="modal" style="max-width:520px">
    <div class="modal-header">
      <span class="modal-title">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" style="margin-right:8px;vertical-align:-2px"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>
        New Note
      </span>
      <button class="modal-close" onclick="closeModal('noteModal')">✕</button>
    </div>
    <div id="noteMsg" class="alert" style="display:none"></div>
    <div class="form-group">
      <label class="form-label">Title</label>
      <input type="text" id="nTitle" class="form-control" placeholder="Note title">
    </div>
    <div class="form-group">
      <label class="form-label">Content</label>
      <textarea id="nContent" class="form-control" rows="6" placeholder="Write your notes here..."></textarea>
    </div>
    <div class="form-grid-2">
      <div class="form-group">
        <label class="form-label">Subject</label>
        <select id="nSubject" class="form-control">
          <option value="">— None —</option>
          <?php foreach($subjects as $s): ?>
          <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="form-group">
        <label class="form-label">Card Color</label>
        <div class="color-swatches" id="noteSwatches">
          <?php foreach(['#6366f1','#8b5cf6','#ec4899','#ef4444','#f97316','#eab308','#22c55e','#06b6d4','#3b82f6','#14b8a6'] as $i => $c): ?>
          <div class="color-swatch <?= $i===0?'selected':'' ?>" style="background:<?= $c ?>" data-color="<?= $c ?>" onclick="selectNoteColor('<?= $c ?>',this)"></div>
          <?php endforeach; ?>
        </div>
        <input type="hidden" id="nColor" value="#6366f1">
      </div>
    </div>
    <button class="btn btn-primary btn-full" onclick="saveNote()" style="margin-top:4px">
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" style="margin-right:6px"><polyline points="20 6 9 17 4 12"/></svg>
      Save Note
    </button>
  </div>
</div>

<!-- ── Add Flashcard Modal ─────────────────────────────────────────── -->
<div class="modal-overlay" id="flashModal">
  <div class="modal" style="max-width:480px">
    <div class="modal-header">
      <span class="modal-title">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" style="margin-right:8px;vertical-align:-2px"><rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8M12 17v4"/></svg>
        New Flashcard
      </span>
      <button class="modal-close" onclick="closeModal('flashModal')">✕</button>
    </div>
    <div id="flashMsg" class="alert" style="display:none"></div>
    <div class="form-group">
      <label class="form-label">Deck Name</label>
      <input type="text" id="fDeck" class="form-control" placeholder="e.g. Physics Formulas" value="General">
    </div>
    <div class="form-group">
      <label class="form-label">Question</label>
      <textarea id="fQ" class="form-control" rows="3" placeholder="Enter your question..."></textarea>
    </div>
    <div class="form-group">
      <label class="form-label">Answer</label>
      <textarea id="fA" class="form-control" rows="3" placeholder="Enter the answer..."></textarea>
    </div>
    <div class="form-grid-2">
      <div class="form-group">
        <label class="form-label">Subject</label>
        <select id="fSubject" class="form-control">
          <option value="">— None —</option>
          <?php foreach($subjects as $s): ?>
          <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['name']) ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="form-group">
        <label class="form-label">Difficulty</label>
        <select id="fDiff" class="form-control">
          <option value="easy">😊 Easy</option>
          <option value="medium" selected>🤔 Medium</option>
          <option value="hard">😓 Hard</option>
        </select>
      </div>
    </div>
    <button class="btn btn-primary btn-full" onclick="saveFlash()" style="margin-top:4px">Add Flashcard</button>
  </div>
</div>

<!-- ── View Note Modal ─────────────────────────────────────────────── -->
<div class="modal-overlay" id="viewNoteModal">
  <div class="modal" style="max-width:600px">
    <div class="modal-header">
      <span class="modal-title" id="vnTitle">Note</span>
      <button class="modal-close" onclick="closeModal('viewNoteModal')">✕</button>
    </div>
    <div id="vnSubject" style="margin-bottom:14px;display:none"></div>
    <div id="vnContent" style="white-space:pre-wrap;line-height:1.8;color:var(--text-secondary);font-size:14px;max-height:60vh;overflow-y:auto"></div>
  </div>
</div>

<!-- ── Quiz Modal ─────────────────────────────────────────────────── -->
<div class="modal-overlay" id="quizModal">
  <div class="modal" style="max-width:500px">
    <div class="modal-header">
      <span class="modal-title" id="quizTitle">Quiz Mode</span>
      <button class="modal-close" onclick="closeModal('quizModal')">✕</button>
    </div>
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px">
      <div id="quizProgress" style="font-size:13px;color:var(--text-muted)"></div>
      <div id="quizProgressBar" style="flex:1;margin-left:14px;height:4px;background:var(--border);border-radius:99px;overflow:hidden">
        <div id="quizProgressFill" style="height:100%;background:linear-gradient(90deg,var(--accent),var(--accent2,#8b5cf6));border-radius:99px;transition:width .3s"></div>
      </div>
    </div>
    <div class="quiz-card">
      <div id="quizText" style="font-size:16px;font-weight:600;color:var(--text-primary);text-align:center;line-height:1.6"></div>
    </div>
    <div class="quiz-answer-box" id="quizAnswer"></div>
    <div id="quizActions" style="text-align:center">
      <button class="btn btn-primary" onclick="revealAnswer()">Show Answer</button>
    </div>
    <div id="quizRating" style="display:none;text-align:center;margin-top:14px">
      <div style="font-size:12px;color:var(--text-muted);margin-bottom:10px">How well did you know it?</div>
      <div style="display:flex;gap:10px;justify-content:center">
        <button class="btn btn-sm" style="background:rgba(239,68,68,.1);color:#f87171;border:1px solid rgba(239,68,68,.25)" onclick="nextCard()">😓 Hard</button>
        <button class="btn btn-secondary btn-sm" onclick="nextCard()">🤔 OK</button>
        <button class="btn btn-sm" style="background:rgba(16,185,129,.1);color:#34d399;border:1px solid rgba(16,185,129,.25)" onclick="nextCard()">😊 Easy</button>
      </div>
    </div>
  </div>
</div>

<?php require_once 'includes/footer.php'; renderFooter(); ?>

<script>
const allDecks = <?= json_encode($decks) ?>;
let currentTab = 'notes';
let quizCards = [], quizIdx = 0;

// ── Tabs ────────────────────────────────────────────────────────────
function switchTab(tab) {
  currentTab = tab;
  document.getElementById('notesTab').style.display = tab === 'notes' ? 'block' : 'none';
  document.getElementById('flashTab').style.display  = tab === 'flash' ? 'block' : 'none';
  document.getElementById('tabNotes').className = 'nf-tab-btn' + (tab === 'notes' ? ' active' : '');
  document.getElementById('tabFlash').className = 'nf-tab-btn' + (tab === 'flash' ? ' active' : '');
  document.getElementById('addBtnLabel').textContent = tab === 'notes' ? 'Add Note' : 'Add Flashcard';
}

function openAddModal() {
  closeModal('noteModal'); closeModal('flashModal');
  document.getElementById(currentTab === 'notes' ? 'noteModal' : 'flashModal').classList.add('active');
}
function closeModal(id) { document.getElementById(id).classList.remove('active'); }

// ── Post helper ─────────────────────────────────────────────────────
async function post(data) {
  const fd = new FormData();
  Object.entries(data).forEach(([k,v]) => fd.append(k, v));
  const r = await fetch(location.href, { method:'POST', headers:{'X-Requested-With':'XMLHttpRequest'}, body:fd });
  return r.json();
}

// ── Color swatches ──────────────────────────────────────────────────
function selectNoteColor(color, el) {
  document.querySelectorAll('#noteSwatches .color-swatch').forEach(s => s.classList.remove('selected'));
  el.classList.add('selected');
  document.getElementById('nColor').value = color;
}

// ── Save note ───────────────────────────────────────────────────────
async function saveNote() {
  const btn = document.querySelector('#noteModal .btn-primary');
  btn.disabled = true; btn.innerHTML = '<span class="spinner"></span> Saving…';
  const data = await post({
    action: 'add_note',
    title: document.getElementById('nTitle').value,
    content: document.getElementById('nContent').value,
    subject_id: document.getElementById('nSubject').value,
    color: document.getElementById('nColor').value
  });
  const msg = document.getElementById('noteMsg');
  msg.style.display = 'flex';
  msg.className = 'alert ' + (data.success ? 'alert-success' : 'alert-error');
  msg.textContent = data.message;
  if (data.success) setTimeout(() => location.reload(), 700);
  else { btn.disabled = false; btn.innerHTML = 'Save Note'; }
}

// ── Save flashcard ──────────────────────────────────────────────────
async function saveFlash() {
  const btn = document.querySelector('#flashModal .btn-primary');
  btn.disabled = true; btn.textContent = 'Adding…';
  const data = await post({
    action:'add_flash',
    deck: document.getElementById('fDeck').value,
    question: document.getElementById('fQ').value,
    answer: document.getElementById('fA').value,
    subject_id: document.getElementById('fSubject').value,
    difficulty: document.getElementById('fDiff').value
  });
  const msg = document.getElementById('flashMsg');
  msg.style.display = 'flex';
  msg.className = 'alert ' + (data.success ? 'alert-success' : 'alert-error');
  msg.textContent = data.message;
  if (data.success) setTimeout(() => location.reload(), 700);
  else { btn.disabled = false; btn.textContent = 'Add Flashcard'; }
}

// ── View note ───────────────────────────────────────────────────────
async function viewNote(id) {
  const data = await post({ action:'get_note', id });
  document.getElementById('vnTitle').textContent = data.title || 'Note';
  document.getElementById('vnContent').textContent = data.content || '';
  const subEl = document.getElementById('vnSubject');
  subEl.style.display = 'none';
  document.getElementById('viewNoteModal').classList.add('active');
}

// ── Delete / pin ────────────────────────────────────────────────────
async function deleteNote(id) {
  if (!(await stConfirm('Delete this note?'))) return;
  await post({ action:'delete_note', id });
  const el = document.getElementById('note-' + id);
  if (el) { el.style.opacity = '0'; el.style.transform = 'scale(.95)'; el.style.transition = 'all .25s'; setTimeout(() => el.remove(), 260); }
}
async function pinNote(id) {
  await post({ action:'pin_note', id });
  location.reload();
}
async function deleteFlash(id) {
  if (!(await stConfirm('Delete this flashcard?'))) return;
  await post({ action:'delete_flash', id });
  const el = document.getElementById('fc-' + id);
  if (el) { el.style.opacity = '0'; el.style.transition = 'opacity .25s'; setTimeout(() => el.remove(), 260); }
}

// ── Toggle flashcard answer ─────────────────────────────────────────
function toggleAnswer(id, btn) {
  const ans = document.getElementById('fca-' + id);
  const show = ans.style.display === 'none' || ans.style.display === '';
  ans.style.display = show ? 'block' : 'none';
  btn.textContent = show ? 'Hide Answer' : 'Show Answer';
}

// ── Toggle deck open/close ──────────────────────────────────────────
function toggleDeck(headerEl) {
  const body = headerEl.nextElementSibling;
  const chevron = headerEl.querySelector('.deck-chevron');
  const isOpen = body.style.display !== 'none';
  body.style.display = isOpen ? 'none' : 'block';
  if (chevron) chevron.style.transform = isOpen ? 'rotate(-90deg)' : 'rotate(0)';
}

// ── Quiz ────────────────────────────────────────────────────────────
function startQuiz(deckName) {
  quizCards = allDecks[deckName] ? [...allDecks[deckName]].sort(() => Math.random() - 0.5) : [];
  quizIdx = 0;
  if (!quizCards.length) return;
  document.getElementById('quizTitle').textContent = deckName;
  document.getElementById('quizModal').classList.add('active');
  showQuizCard();
}

function showQuizCard() {
  const total = quizCards.length;
  if (quizIdx >= total) {
    document.getElementById('quizText').innerHTML = '<div style="font-size:36px;margin-bottom:12px">🎉</div><div style="font-size:18px;font-weight:700">Quiz Complete!</div><div style="font-size:13px;color:var(--text-muted);margin-top:8px">Reviewed all ' + total + ' cards</div>';
    document.getElementById('quizAnswer').style.display = 'none';
    document.getElementById('quizRating').style.display = 'none';
    document.getElementById('quizActions').innerHTML = '<button class="btn btn-primary" onclick="closeModal(\'quizModal\')">Done ✓</button>';
    document.getElementById('quizProgress').textContent = 'Complete!';
    document.getElementById('quizProgressFill').style.width = '100%';
    return;
  }
  const c = quizCards[quizIdx];
  document.getElementById('quizProgress').textContent = (quizIdx + 1) + ' / ' + total;
  document.getElementById('quizProgressFill').style.width = ((quizIdx / total) * 100) + '%';
  document.getElementById('quizText').textContent = c.question;
  document.getElementById('quizAnswer').style.display = 'none';
  document.getElementById('quizAnswer').textContent = c.answer;
  document.getElementById('quizRating').style.display = 'none';
  document.getElementById('quizActions').innerHTML = '<button class="btn btn-primary" onclick="revealAnswer()">Show Answer</button>';
}

function revealAnswer() {
  document.getElementById('quizAnswer').style.display = 'block';
  document.getElementById('quizActions').innerHTML = '';
  document.getElementById('quizRating').style.display = 'block';
  post({ action:'review_flash', id: quizCards[quizIdx].id });
}

function nextCard() {
  quizIdx++;
  showQuizCard();
}

// spinner style
const s = document.createElement('style');
s.textContent = '.spinner{display:inline-block;width:13px;height:13px;border:2px solid rgba(255,255,255,.3);border-top-color:#fff;border-radius:50%;animation:spin .65s linear infinite;vertical-align:middle} @keyframes spin{to{transform:rotate(360deg)}}';
document.head.appendChild(s);
</script>