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

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

    if ($action === 'add') {
        $subId = (int)($_POST['subject_id'] ?? 0) ?: null;
        $day   = sanitize($_POST['day'] ?? '');
        $start = sanitize($_POST['start_time'] ?? '');
        $end   = sanitize($_POST['end_time'] ?? '');
        $label = sanitize($_POST['label'] ?? '');
        $color = sanitize($_POST['color'] ?? '#6366f1');

        $validDays = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
        if (!in_array($day, $validDays)) jsonResponse(['success'=>false,'message'=>'Invalid day.']);
        if (!$start || !$end)           jsonResponse(['success'=>false,'message'=>'Please set start and end time.']);
        if ($start >= $end)             jsonResponse(['success'=>false,'message'=>'End time must be after start time.']);

        $stmt = $pdo->prepare("INSERT INTO timetable (user_id,subject_id,day_of_week,start_time,end_time,label,color) VALUES (?,?,?,?,?,?,?)");
        $stmt->execute([$uid,$subId,$day,$start,$end,$label,$color]);
        jsonResponse(['success'=>true,'message'=>'Slot added!','id'=>$pdo->lastInsertId()]);
    }

    if ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        $pdo->prepare("DELETE FROM timetable WHERE id=? AND user_id=?")->execute([$id,$uid]);
        jsonResponse(['success'=>true]);
    }

    if ($action === 'toggle') {
        $id = (int)($_POST['id'] ?? 0);
        $pdo->prepare("UPDATE timetable SET is_active = NOT is_active WHERE id=? AND user_id=?")->execute([$id,$uid]);
        jsonResponse(['success'=>true]);
    }
}

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

$slots = $pdo->prepare("
    SELECT t.*, s.name as subject_name, s.color as subject_color
    FROM timetable t
    LEFT JOIN subjects s ON t.subject_id = s.id
    WHERE t.user_id = ?
    ORDER BY FIELD(t.day_of_week,'Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'), t.start_time
");
$slots->execute([$uid]);
$slots = $slots->fetchAll();

// Group by day
$days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'];
$dayShort = ['Monday'=>'Mon','Tuesday'=>'Tue','Wednesday'=>'Wed','Thursday'=>'Thu','Friday'=>'Fri','Saturday'=>'Sat','Sunday'=>'Sun'];
$slotsByDay = array_fill_keys($days, []);
foreach ($slots as $s) $slotsByDay[$s['day_of_week']][] = $s;

$totalSlots  = count($slots);
$activeSlots = count(array_filter($slots, fn($s) => $s['is_active']));
$todayDay    = date('l'); // e.g. "Monday"

require_once 'includes/header.php';
renderHeader('Timetable', 'timetable');
?>

<style>
/* ── Page Variables ───────────────────────────────────────── */
:root {
  --tt-radius: 14px;
  --tt-slot-radius: 10px;
  --tt-today-glow: 0 0 0 2px rgba(99,102,241,.35), 0 4px 20px rgba(99,102,241,.12);
}

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

/* ── Stats Row ──────────────────────────────────────────────── */
.tt-stats {
  display: flex;
  gap: 12px;
  margin-bottom: 22px;
  flex-wrap: wrap;
}
.tt-stat-card {
  flex: 1;
  min-width: 130px;
  background: var(--bg-card);
  border: 1px solid var(--border);
  border-radius: var(--tt-radius);
  padding: 14px 18px;
  display: flex;
  align-items: center;
  gap: 12px;
}
.tt-stat-icon {
  width: 38px;
  height: 38px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 17px;
  flex-shrink: 0;
}
.tt-stat-val {
  font-size: 22px;
  font-weight: 800;
  color: var(--text-primary);
  line-height: 1;
}
.tt-stat-label {
  font-size: 11px;
  color: var(--text-muted);
  margin-top: 3px;
  font-weight: 500;
}

/* ── Day Tabs ───────────────────────────────────────────────── */
.tt-day-tabs {
  display: flex;
  gap: 6px;
  margin-bottom: 18px;
  overflow-x: auto;
  padding-bottom: 4px;
  scrollbar-width: none;
}
.tt-day-tabs::-webkit-scrollbar { display: none; }
.tt-day-tab {
  flex-shrink: 0;
  padding: 7px 14px;
  border-radius: 10px;
  border: 1px solid var(--border);
  background: var(--bg-secondary);
  color: var(--text-secondary);
  font-size: 12px;
  font-weight: 600;
  cursor: pointer;
  transition: all .18s;
  position: relative;
  white-space: nowrap;
}
.tt-day-tab:hover {
  border-color: var(--accent);
  color: var(--accent);
  background: rgba(99,102,241,.06);
}
.tt-day-tab.active {
  background: rgba(99,102,241,.12);
  border-color: rgba(99,102,241,.5);
  color: var(--accent);
  font-weight: 700;
}
.tt-day-tab.today {
  border-color: rgba(99,102,241,.4);
}
.tt-day-tab.today::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 50%;
  transform: translateX(-50%);
  width: 5px;
  height: 5px;
  border-radius: 50%;
  background: var(--accent);
}
.tt-day-tab .tt-slot-count {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 17px;
  height: 17px;
  border-radius: 99px;
  background: rgba(99,102,241,.18);
  color: var(--accent);
  font-size: 10px;
  font-weight: 800;
  margin-left: 5px;
}

/* ── Slot Row (timeline style) ──────────────────────────────── */
.tt-slot-row {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  transition: opacity .2s;
}
.tt-slot-row.is-inactive { opacity: 0.38; }

.tt-slot-card {
  flex: 1;
  background: var(--bg-card);
  border: 1px solid var(--border);
  border-radius: 12px;
  padding: 12px 14px;
  transition: box-shadow .18s, transform .18s;
}
.tt-slot-card:hover {
  box-shadow: 0 4px 18px rgba(0,0,0,.12);
  transform: translateY(-1px);
}

/* ── Today badge ──────────────────────────────────────────── */
.tt-today-badge {
  font-size: 9px;
  font-weight: 700;
  background: rgba(99,102,241,.15);
  color: var(--accent);
  border: 1px solid rgba(99,102,241,.3);
  border-radius: 99px;
  padding: 2px 7px;
  letter-spacing: .3px;
}

/* ── Modal Overrides ────────────────────────────────────────── */
.tt-modal-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

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

/* ── Responsive ──────────────────────────────────────────────── */
@media (max-width: 768px) {
  .tt-grid { grid-template-columns: repeat(7, minmax(130px,1fr)); }
}
</style>

<!-- Page Header -->
<div class="tt-page-header">
  <div>
    <div class="tt-page-title">📅 Study Timetable</div>
    <div class="tt-page-sub">Plan and manage your weekly study schedule</div>
  </div>
  <button class="btn btn-primary" onclick="openModal()" style="flex-shrink:0">
    <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" stroke-linejoin="round" style="margin-right:6px"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
    Add Slot
  </button>
</div>

<!-- Stats -->
<div class="tt-stats">
  <div class="tt-stat-card">
    <div class="tt-stat-icon" style="background:rgba(99,102,241,.12)">📋</div>
    <div>
      <div class="tt-stat-val"><?= $totalSlots ?></div>
      <div class="tt-stat-label">Total Slots</div>
    </div>
  </div>
  <div class="tt-stat-card">
    <div class="tt-stat-icon" style="background:rgba(16,185,129,.12)">✅</div>
    <div>
      <div class="tt-stat-val"><?= $activeSlots ?></div>
      <div class="tt-stat-label">Active Slots</div>
    </div>
  </div>
  <div class="tt-stat-card">
    <div class="tt-stat-icon" style="background:rgba(245,158,11,.12)">📚</div>
    <div>
      <div class="tt-stat-val"><?= count($slotsByDay[$todayDay]) ?></div>
      <div class="tt-stat-label">Today's Classes</div>
    </div>
  </div>
  <div class="tt-stat-card">
    <div class="tt-stat-icon" style="background:rgba(139,92,246,.12)">📖</div>
    <div>
      <div class="tt-stat-val"><?= count($subjects) ?></div>
      <div class="tt-stat-label">Subjects</div>
    </div>
  </div>
</div>

<!-- Day Tabs -->
<div class="tt-day-tabs">
  <?php foreach ($days as $day): ?>
  <div class="tt-day-tab <?= $day === $todayDay ? 'today' : '' ?> <?= $day === $todayDay ? 'active' : '' ?>"
       data-day="<?= $day ?>"
       onclick="selectDay('<?= $day ?>', this)">
    <?= $dayShort[$day] ?>
    <?php if (count($slotsByDay[$day]) > 0): ?>
    <span class="tt-slot-count"><?= count($slotsByDay[$day]) ?></span>
    <?php endif; ?>
  </div>
  <?php endforeach; ?>
</div>

<!-- Single Day View -->
<div id="ttDayView">
  <?php foreach ($days as $day): ?>
  <div class="tt-single-day" id="dayview-<?= $day ?>" style="display:<?= $day === $todayDay ? 'block' : 'none' ?>">

    <!-- Day header bar -->
    <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:16px;gap:12px;flex-wrap:wrap">
      <div style="display:flex;align-items:center;gap:10px">
        <div style="font-size:18px;font-weight:800;color:var(--text-primary);font-family:'Sora',sans-serif"><?= $day ?></div>
        <?php if ($day === $todayDay): ?>
        <div class="tt-today-badge">Today</div>
        <?php endif; ?>
        <?php if (count($slotsByDay[$day]) > 0): ?>
        <div style="font-size:12px;color:var(--text-muted);background:var(--bg-secondary);border:1px solid var(--border);border-radius:99px;padding:2px 10px">
          <?= count($slotsByDay[$day]) ?> slot<?= count($slotsByDay[$day]) > 1 ? 's' : '' ?>
        </div>
        <?php endif; ?>
      </div>
      <button class="btn btn-primary" onclick="openModal('<?= $day ?>')" style="font-size:12px;padding:7px 14px">
        <svg xmlns="http://www.w3.org/2000/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"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
        Add to <?= $dayShort[$day] ?>
      </button>
    </div>

    <?php if (empty($slotsByDay[$day])): ?>
    <!-- Empty state -->
    <div style="text-align:center;padding:56px 20px;background:var(--bg-card);border:1px dashed var(--border);border-radius:14px">
      <div style="font-size:40px;margin-bottom:12px">📭</div>
      <div style="font-size:15px;font-weight:700;color:var(--text-primary);margin-bottom:6px">No slots for <?= $day ?></div>
      <div style="font-size:13px;color:var(--text-muted);margin-bottom:20px">Add your first study slot for this day</div>
      <button class="btn btn-primary" onclick="openModal('<?= $day ?>')">
        <svg xmlns="http://www.w3.org/2000/svg" width="13" height="13" 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>
        Add Slot
      </button>
    </div>

    <?php else: ?>
    <!-- Slots list -->
    <div style="display:flex;flex-direction:column;gap:10px">
      <?php foreach ($slotsByDay[$day] as $sl): ?>
      <?php
        $slotColor = htmlspecialchars($sl['color'] ?? $sl['subject_color'] ?? '#6366f1');
        $slotLabel = htmlspecialchars($sl['label'] ?: ($sl['subject_name'] ?: 'Study'));
        $startFmt  = date('g:ia', strtotime($sl['start_time']));
        $endFmt    = date('g:ia', strtotime($sl['end_time']));
        // Duration in minutes
        $durMins   = (strtotime($sl['end_time']) - strtotime($sl['start_time'])) / 60;
        $durStr    = $durMins >= 60 ? floor($durMins/60).'h '.($durMins%60 ? ($durMins%60).'m' : '') : $durMins.'m';
        $durStr    = trim($durStr);
      ?>
      <div class="tt-slot-row <?= $sl['is_active'] ? '' : 'is-inactive' ?>">
        <!-- Color bar -->
        <div style="width:4px;flex-shrink:0;border-radius:99px;background:<?= $slotColor ?>;align-self:stretch;min-height:52px"></div>
        <!-- Time column -->
        <div style="width:80px;flex-shrink:0;text-align:right;padding-right:6px">
          <div style="font-size:13px;font-weight:700;color:var(--text-primary)"><?= $startFmt ?></div>
          <div style="font-size:11px;color:var(--text-muted);margin-top:2px"><?= $endFmt ?></div>
          <div style="font-size:10px;color:var(--text-muted);margin-top:3px;background:var(--bg-secondary);border:1px solid var(--border);border-radius:99px;padding:1px 6px;display:inline-block"><?= $durStr ?></div>
        </div>
        <!-- Dot connector -->
        <div style="display:flex;flex-direction:column;align-items:center;gap:2px;flex-shrink:0">
          <div style="width:10px;height:10px;border-radius:50%;border:2px solid <?= $slotColor ?>;background:var(--bg-primary)"></div>
          <div style="width:2px;flex:1;background:var(--border);min-height:30px"></div>
        </div>
        <!-- Content card -->
        <div class="tt-slot-card" style="border-left:3px solid <?= $slotColor ?>">
          <div style="display:flex;align-items:flex-start;justify-content:space-between;gap:8px">
            <div style="min-width:0">
              <div style="font-size:14px;font-weight:700;color:var(--text-primary);margin-bottom:4px"><?= $slotLabel ?></div>
              <?php if ($sl['subject_name']): ?>
              <div style="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">
                <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg>
                <?= htmlspecialchars($sl['subject_name']) ?>
              </div>
              <?php endif; ?>
              <?php if (!$sl['is_active']): ?>
              <div style="display:inline-flex;align-items:center;gap:4px;font-size:10px;font-weight:600;color:#f59e0b;background:rgba(245,158,11,.1);border:1px solid rgba(245,158,11,.25);border-radius:99px;padding:2px 8px;margin-left:4px">
                Inactive
              </div>
              <?php endif; ?>
            </div>
            <div style="display:flex;gap:6px;flex-shrink:0">
              <button onclick="deleteSlot(<?= $sl['id'] ?>)" title="Delete"
                style="width:30px;height:30px;border-radius:8px;border:1px solid rgba(239,68,68,.2);background:rgba(239,68,68,.08);color:#ef4444;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:all .15s;font-size:12px"
                onmouseover="this.style.background='rgba(239,68,68,.2)'"
                onmouseout="this.style.background='rgba(239,68,68,.08)'">
                <svg width="12" height="12" 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"/><path d="M10 11v6"/><path d="M14 11v6"/></svg>
              </button>
            </div>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
    </div>
    <?php endif; ?>

  </div>
  <?php endforeach; ?>
</div>

<!-- Add Slot Modal -->
<div class="modal-overlay" id="ttModal">
  <div class="modal" style="max-width:460px">
    <div class="modal-header">
      <span class="modal-title">
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right:8px;vertical-align:-2px"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
        Add Schedule Slot
      </span>
      <button class="modal-close" onclick="closeModal()">✕</button>
    </div>

    <div id="ttMsg" class="alert" style="display:none"></div>

    <div class="form-group">
      <label class="form-label">Day</label>
      <select id="ttDay" class="form-control">
        <?php foreach ($days as $d): ?>
        <option <?= $d === $todayDay ? 'selected' : '' ?>><?= $d ?></option>
        <?php endforeach; ?>
      </select>
    </div>

    <div class="tt-modal-grid">
      <div class="form-group">
        <label class="form-label">Start Time</label>
        <input type="time" id="ttStart" class="form-control" value="08:00">
      </div>
      <div class="form-group">
        <label class="form-label">End Time</label>
        <input type="time" id="ttEnd" class="form-control" value="09:00">
      </div>
    </div>

    <div class="form-group">
      <label class="form-label">Subject <span style="color:var(--text-muted);font-weight:400">(optional)</span></label>
      <select id="ttSubject" class="form-control">
        <option value="">— No subject —</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">Label <span style="color:var(--text-muted);font-weight:400">(optional)</span></label>
      <input type="text" id="ttLabel" class="form-control" placeholder="e.g. Revision, Past Papers, Lecture">
    </div>

    <div class="form-group">
      <label class="form-label">Color</label>
      <div class="tt-color-swatches" id="ttSwatches">
        <?php
          $presetColors = ['#6366f1','#a855f7','#ec4899','#ef4444','#f97316','#eab308','#22c55e','#14b8a6','#06b6d4','#3b82f6'];
          foreach ($presetColors as $i => $c):
        ?>
        <div class="tt-swatch <?= $i === 0 ? 'selected' : '' ?>"
             style="background:<?= $c ?>"
             data-color="<?= $c ?>"
             onclick="selectColor('<?= $c ?>', this)"></div>
        <?php endforeach; ?>
      </div>
      <input type="hidden" id="ttColor" value="#6366f1">
    </div>

    <button class="btn btn-primary btn-full" onclick="saveSlot()" style="margin-top:4px">
      <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" stroke-linejoin="round" style="margin-right:6px"><polyline points="20 6 9 17 4 12"/></svg>
      Save Slot
    </button>
  </div>
</div>

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

<script>
// ── Modal ─────────────────────────────────────────────────────────
function openModal(presetDay) {
  if (presetDay) document.getElementById('ttDay').value = presetDay;
  document.getElementById('ttModal').classList.add('active');
}
function closeModal() {
  document.getElementById('ttModal').classList.remove('active');
  var msg = document.getElementById('ttMsg');
  msg.style.display = 'none';
}

// ── Color picker ──────────────────────────────────────────────────
function selectColor(color, el) {
  document.querySelectorAll('.tt-swatch').forEach(function(s){ s.classList.remove('selected'); });
  el.classList.add('selected');
  document.getElementById('ttColor').value = color;
}

// ── Save slot ─────────────────────────────────────────────────────
async function saveSlot() {
  var btn = document.querySelector('#ttModal .btn-primary');
  btn.disabled = true;
  btn.innerHTML = '<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;animation:spin .7s linear infinite"><polyline points="23 4 23 10 17 10"/><path d="M20.49 15a9 9 0 1 1-.07-8.2"/></svg>Saving…';

  var fd = new FormData();
  fd.append('action',     'add');
  fd.append('day',        document.getElementById('ttDay').value);
  fd.append('start_time', document.getElementById('ttStart').value);
  fd.append('end_time',   document.getElementById('ttEnd').value);
  fd.append('subject_id', document.getElementById('ttSubject').value);
  fd.append('label',      document.getElementById('ttLabel').value);
  fd.append('color',      document.getElementById('ttColor').value);

  var res  = await fetch(location.href, {method:'POST', headers:{'X-Requested-With':'XMLHttpRequest'}, body:fd});
  var data = await res.json();

  var msg = document.getElementById('ttMsg');
  msg.style.display = 'flex';
  msg.className = 'alert ' + (data.success ? 'alert-success' : 'alert-error');
  msg.textContent = data.message;

  if (data.success) {
    setTimeout(function(){ location.reload(); }, 700);
  } else {
    btn.disabled = false;
    btn.innerHTML = '<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" stroke-linejoin="round" style="margin-right:6px"><polyline points="20 6 9 17 4 12"/></svg>Save Slot';
  }
}

// ── Delete slot ───────────────────────────────────────────────────
async function deleteSlot(id) {
  if (!(await stConfirm('Delete this slot?'))) return;
  var fd = new FormData();
  fd.append('action','delete');
  fd.append('id', id);
  await fetch(location.href, {method:'POST', headers:{'X-Requested-With':'XMLHttpRequest'}, body:fd});
  location.reload();
}

// ── Day selector ──────────────────────────────────────────────────
function selectDay(day, tabEl) {
  document.querySelectorAll('.tt-day-tab').forEach(function(t){ t.classList.remove('active'); });
  tabEl.classList.add('active');
  document.querySelectorAll('.tt-single-day').forEach(function(d){ d.style.display = 'none'; });
  var target = document.getElementById('dayview-' + day);
  if (target) { target.style.display = 'block'; }
}

// ── Animations ───────────────────────────────────────────────────
var extraStyle = document.createElement('style');
extraStyle.textContent = '@keyframes spin { from{transform:rotate(0deg)} to{transform:rotate(360deg)} }';
document.head.appendChild(extraStyle);

// ── Push Notification Permission (Timetable Page) ──────────────────────────────────
(function() {
  var VAPID_KEY = '<?= defined("VAPID_PUBLIC_KEY") ? VAPID_PUBLIC_KEY : "" ?>';
  var SITE_URL  = '<?= defined("SITE_URL") ? SITE_URL : "" ?>';

  function urlBase64ToUint8Array(b64) {
    var pad = '='.repeat((4 - b64.length % 4) % 4);
    var raw = atob((b64 + pad).replace(/-/g,'+').replace(/_/g,'/'));
    var out = new Uint8Array(raw.length);
    for (var i = 0; i < raw.length; i++) out[i] = raw.charCodeAt(i);
    return out;
  }

  // Save subscription to server, then send welcome push
  function saveSub(sub) {
    // sub could be a PushSubscription object or already a plain object
    var endpoint, p256dh, auth;
    if (typeof sub.toJSON === 'function') {
      var j = sub.toJSON();
      endpoint = j.endpoint || sub.endpoint || '';
      p256dh   = (j.keys && j.keys.p256dh)  ? j.keys.p256dh  : (sub.getKey ? btoa(String.fromCharCode.apply(null, new Uint8Array(sub.getKey('p256dh')))) : '');
      auth     = (j.keys && j.keys.auth)     ? j.keys.auth    : (sub.getKey ? btoa(String.fromCharCode.apply(null, new Uint8Array(sub.getKey('auth'))))    : '');
    } else {
      endpoint = sub.endpoint || '';
      p256dh   = (sub.keys && sub.keys.p256dh) ? sub.keys.p256dh : '';
      auth     = (sub.keys && sub.keys.auth)    ? sub.keys.auth   : '';
    }

    if (!endpoint) { console.warn('Push: no endpoint in subscription'); return; }

    var fd = new FormData();
    fd.append('action',   'subscribe');
    fd.append('endpoint', endpoint);
    fd.append('p256dh',   p256dh);
    fd.append('auth',     auth);
    fetch(SITE_URL + '/api/push-subscribe.php', {
      method: 'POST',
      headers: { 'X-Requested-With': 'XMLHttpRequest' },
      body: fd
    }).then(function(r){ return r.json(); }).then(function(d){
      if (d && d.success) {
        fetch(SITE_URL + '/api/push-send.php', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
          body: JSON.stringify({ action: 'send_timetable_welcome' })
        }).catch(function(){});
      }
    }).catch(function(){});
  }

  function doSubscribe(reg) {
    reg.pushManager.getSubscription().then(function(ex) {
      if (ex) { saveSub(ex); return; }
      reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: urlBase64ToUint8Array(VAPID_KEY) })
        .then(saveSub).catch(function(e){ console.warn('Push sub failed:', e); });
    });
  }

  function showBanner() {
    if (document.getElementById('pushBanner')) return;
    var b = document.createElement('div');
    b.id = 'pushBanner';
    b.innerHTML = '<div style="display:flex;align-items:center;gap:12px;flex-wrap:wrap">'
      + '<div style="font-size:22px">\uD83D\uDD14</div>'
      + '<div style="flex:1;min-width:180px"><div style="font-size:13px;font-weight:700;color:var(--text-primary)">Enable Timetable Reminders</div>'
      + '<div style="font-size:12px;color:var(--text-muted);margin-top:2px">Get notified before your study slots start</div></div>'
      + '<div style="display:flex;gap:8px;flex-shrink:0">'
      + '<button id="pushAllow" style="padding:7px 16px;border-radius:8px;border:none;background:var(--accent,#6366f1);color:#fff;font-size:12px;font-weight:700;cursor:pointer">Enable</button>'
      + '<button id="pushDeny" style="padding:7px 14px;border-radius:8px;border:1px solid var(--border);background:transparent;color:var(--text-muted);font-size:12px;cursor:pointer">Not now</button>'
      + '</div></div>';
    Object.assign(b.style, {
      position:'fixed', bottom:'24px', left:'50%', transform:'translateX(-50%)',
      width:'calc(100% - 48px)', maxWidth:'560px', background:'var(--bg-card)',
      border:'1px solid var(--border)', borderRadius:'14px', padding:'14px 18px',
      boxShadow:'0 8px 32px rgba(0,0,0,.25)', zIndex:'9999',
      animation:'slideUpBanner .35s ease'
    });
    var st = document.createElement('style');
    st.textContent = '@keyframes slideUpBanner{from{opacity:0;transform:translateX(-50%) translateY(20px)}to{opacity:1;transform:translateX(-50%) translateY(0)}}';
    document.head.appendChild(st);
    document.body.appendChild(b);

    document.getElementById('pushAllow').onclick = function() {
      b.remove();
      Notification.requestPermission().then(function(perm) {
        if (perm !== 'granted') return;
        navigator.serviceWorker.ready.then(doSubscribe);
      });
    };
    document.getElementById('pushDeny').onclick = function() {
      b.remove();
      localStorage.setItem('pushDeniedAt', Date.now());
    };
  }

  function init() {
    if (!('Notification' in window) || !('PushManager' in window) || !VAPID_KEY) return;
    if (Notification.permission === 'denied') return;

    var deniedAt = parseInt(localStorage.getItem('pushDeniedAt') || '0', 10);
    if (Date.now() - deniedAt < 3 * 24 * 60 * 60 * 1000) return;

    if (!('serviceWorker' in navigator)) return;

    navigator.serviceWorker.register(SITE_URL + '/sw.js', { scope: SITE_URL + '/' })
      .then(function(reg) {
        if (Notification.permission === 'granted') {
          doSubscribe(reg); return;
        }
        setTimeout(showBanner, 1800);
      }).catch(function(){});
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();

</script>