<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';
requireLogin();
$uid     = $_SESSION['user_id'];
$siteUrl = defined('SITE_URL')  ? SITE_URL  : '';
$siteName= defined('SITE_NAME') ? SITE_NAME : 'StudyTrack';

// ── Download handlers (must run before any HTML output) ─────────────────
$dl = $_GET['download'] ?? '';
if ($dl === 'changelog' || $dl === 'txt' || $dl === 'json') {
    try {
        $dlUpdates = $pdo->query("SELECT * FROM site_updates WHERE is_published=1 ORDER BY created_at DESC")->fetchAll();
    } catch(PDOException $e) { $dlUpdates = []; }

    if ($dl === 'changelog' || $dl === 'txt') {
        $out  = "========================================\n";
        $out .= "  $siteName - Site Changelog\n";
        $out .= "  Generated: " . date('F j, Y g:i A') . "\n";
        $out .= "========================================\n\n";
        $typeMap = ['new'=>'NEW FEATURE','improvement'=>'IMPROVEMENT','fix'=>'BUG FIX','security'=>'SECURITY UPDATE'];
        foreach ($dlUpdates as $u) {
            $out .= "----------------------------------------\n";
            $out .= "  Version " . $u['version'] . " — " . ($typeMap[$u['update_type']] ?? strtoupper($u['update_type'])) . "\n";
            $out .= "  " . $u['title'] . "\n";
            $out .= "  Released: " . date('F j, Y', strtotime($u['created_at'])) . "\n";
            $out .= "----------------------------------------\n";
            foreach (array_filter(array_map('trim', explode("\n", $u['description']))) as $line) {
                $out .= "  • $line\n";
            }
            $out .= "\n";
        }
        $out .= "========================================\n  Thank you for using $siteName!\n========================================\n";
        header('Content-Type: text/plain; charset=utf-8');
        header('Content-Disposition: attachment; filename="' . $siteName . '-changelog-' . date('Y-m-d') . '.txt"');
        echo $out; exit;
    }

    if ($dl === 'json') {
        $out = array_map(fn($u) => ['version'=>$u['version'],'title'=>$u['title'],'description'=>$u['description'],'type'=>$u['update_type'],'date'=>$u['created_at']], $dlUpdates);
        header('Content-Type: application/json');
        header('Content-Disposition: attachment; filename="' . $siteName . '-changelog-' . date('Y-m-d') . '.json"');
        echo json_encode(['site'=>$siteName,'generated'=>date('c'),'updates'=>$out], JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE);
        exit;
    }
}

// ── Auto-create tables if not exist ─────────────────────────────────────
try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `site_updates` (
        `id` INT AUTO_INCREMENT PRIMARY KEY,
        `version` VARCHAR(20) NOT NULL,
        `title` VARCHAR(255) NOT NULL,
        `description` TEXT NOT NULL,
        `update_type` ENUM('new','improvement','fix','security') DEFAULT 'new',
        `is_published` TINYINT(1) DEFAULT 1,
        `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB");
    $pdo->exec("CREATE TABLE IF NOT EXISTS `user_update_reads` (
        `user_id` INT NOT NULL,
        `read_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (`user_id`)
    ) ENGINE=InnoDB");
} catch(PDOException $e) {}

// ── Mark all updates as READ (auto-read on page open) ────────────────────
try {
    $pdo->prepare("INSERT INTO user_update_reads (user_id, read_at) VALUES (?, NOW())
                   ON DUPLICATE KEY UPDATE read_at = NOW()")->execute([$uid]);
} catch(PDOException $e) {}

// ── Load published updates ───────────────────────────────────────────────
$updates = [];
try {
    $updates = $pdo->query("SELECT * FROM site_updates WHERE is_published=1 ORDER BY created_at DESC")->fetchAll();
} catch(PDOException $e) {}

// ── Load user info ───────────────────────────────────────────────────────
$userQ = $pdo->prepare("SELECT * FROM users WHERE id=?");
$userQ->execute([$uid]);
$user = $userQ->fetch();

$siteUrl  = defined('SITE_URL')  ? SITE_URL  : '';
$siteName = defined('SITE_NAME') ? SITE_NAME : 'StudyTrack';

// ── Type config ──────────────────────────────────────────────────────────
$typeConfig = [
    'new'         => ['icon'=>'✨', 'label'=>'New Feature',   'color'=>'#10b981', 'bg'=>'rgba(16,185,129,0.12)',  'border'=>'rgba(16,185,129,0.3)'],
    'improvement' => ['icon'=>'⚡', 'label'=>'Improvement',   'color'=>'#6366f1', 'bg'=>'rgba(99,102,241,0.12)',  'border'=>'rgba(99,102,241,0.3)'],
    'fix'         => ['icon'=>'🔧', 'label'=>'Bug Fix',       'color'=>'#06b6d4', 'bg'=>'rgba(6,182,212,0.12)',   'border'=>'rgba(6,182,212,0.3)'],
    'security'    => ['icon'=>'🔒', 'label'=>'Security',      'color'=>'#ef4444', 'bg'=>'rgba(239,68,68,0.12)',   'border'=>'rgba(239,68,68,0.3)'],
];

require_once 'includes/header.php';
renderHeader('Settings', 'settings');
?>

<!-- ══ PAGE HEADER ══════════════════════════════════════════════════════ -->
<div style="margin-bottom:28px">
  <h1 style="font-size:22px;font-weight:800;color:var(--text-primary);margin:0 0 4px">⚙️ Settings</h1>
  <p style="font-size:13px;color:var(--text-muted);margin:0">App preferences and latest updates</p>
</div>

<!-- ══ TABS ════════════════════════════════════════════════════════════ -->
<div style="display:flex;gap:6px;margin-bottom:24px;border-bottom:1px solid var(--border);padding-bottom:0" id="settingsTabs">
  <button class="st-tab active" data-tab="updates" onclick="switchTab('updates',this)"
    style="padding:10px 20px;border:none;background:none;cursor:pointer;font-size:14px;font-weight:600;color:var(--accent);border-bottom:2px solid var(--accent);margin-bottom:-1px;border-radius:0;transition:all 0.2s">
    🆕 What's New
    <?php if(!empty($updates)): ?>
    <span id="updateCountBadge" style="display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;border-radius:50%;background:var(--accent);color:#fff;font-size:11px;font-weight:700;margin-left:6px"><?= count($updates) ?></span>
    <?php endif; ?>
  </button>
  <button class="st-tab" data-tab="appearance" onclick="switchTab('appearance',this)"
    style="padding:10px 20px;border:none;background:none;cursor:pointer;font-size:14px;font-weight:600;color:var(--text-secondary);border-bottom:2px solid transparent;margin-bottom:-1px;border-radius:0;transition:all 0.2s">
    🎨 Appearance
  </button>
  <button class="st-tab" data-tab="account" onclick="switchTab('account',this)"
    style="padding:10px 20px;border:none;background:none;cursor:pointer;font-size:14px;font-weight:600;color:var(--text-secondary);border-bottom:2px solid transparent;margin-bottom:-1px;border-radius:0;transition:all 0.2s">
    👤 Account
  </button>
</div>

<!-- ══ TAB: WHAT'S NEW ════════════════════════════════════════════════ -->
<div id="tab-updates" class="st-tab-content">

  <!-- Top bar -->
  <div style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:20px">
    <div>
      <div style="font-size:16px;font-weight:700;color:var(--text-primary)">Site Updates &amp; Changelog</div>
      <div style="font-size:13px;color:var(--text-muted);margin-top:2px">All new features, improvements and bug fixes</div>
    </div>
    <?php if($updates): ?>
    <button onclick="startDownload()" id="dlBtn"
      style="display:inline-flex;align-items:center;gap:8px;padding:10px 20px;border-radius:12px;
             background:linear-gradient(135deg,#6366f1,#8b5cf6);border:none;
             color:#fff;font-size:13px;font-weight:700;cursor:pointer;
             box-shadow:0 4px 14px rgba(99,102,241,0.35);transition:all 0.2s">
      <svg id="dlIcon" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
      <span id="dlBtnText">Download Changelog</span>
    </button>
    <?php endif; ?>
  </div>

  <!-- Filter chips -->
  <?php if($updates): ?>
  <div style="display:flex;gap:7px;flex-wrap:wrap;margin-bottom:22px" id="filterRow">
    <button class="uf-chip active" data-filter="all" onclick="filterUpdates('all',this)"
      style="padding:6px 14px;border-radius:20px;border:1px solid var(--accent);background:var(--accent);color:#fff;font-size:12px;font-weight:600;cursor:pointer;transition:all 0.2s">All</button>
    <button class="uf-chip" data-filter="new" onclick="filterUpdates('new',this)"
      style="padding:6px 14px;border-radius:20px;border:1px solid rgba(16,185,129,0.35);background:rgba(16,185,129,0.1);color:#10b981;font-size:12px;font-weight:600;cursor:pointer;transition:all 0.2s">✨ New Features</button>
    <button class="uf-chip" data-filter="improvement" onclick="filterUpdates('improvement',this)"
      style="padding:6px 14px;border-radius:20px;border:1px solid rgba(99,102,241,0.35);background:rgba(99,102,241,0.1);color:#6366f1;font-size:12px;font-weight:600;cursor:pointer;transition:all 0.2s">⚡ Improvements</button>
    <button class="uf-chip" data-filter="fix" onclick="filterUpdates('fix',this)"
      style="padding:6px 14px;border-radius:20px;border:1px solid rgba(6,182,212,0.35);background:rgba(6,182,212,0.1);color:#06b6d4;font-size:12px;font-weight:600;cursor:pointer;transition:all 0.2s">🔧 Bug Fixes</button>
    <button class="uf-chip" data-filter="security" onclick="filterUpdates('security',this)"
      style="padding:6px 14px;border-radius:20px;border:1px solid rgba(239,68,68,0.35);background:rgba(239,68,68,0.1);color:#ef4444;font-size:12px;font-weight:600;cursor:pointer;transition:all 0.2s">🔒 Security</button>
  </div>

  <!-- Timeline -->
  <div style="position:relative;padding-left:26px" id="updateTimeline">
    <div style="position:absolute;left:9px;top:0;bottom:0;width:2px;background:var(--border);border-radius:2px"></div>
    <?php foreach($updates as $i => $u):
      $cfg = $typeConfig[$u['update_type']] ?? $typeConfig['new'];
      $isFirst = ($i === 0);
      $lines = array_filter(array_map('trim', explode("\n", $u['description'])));
    ?>
    <div class="upd-item" data-type="<?= $u['update_type'] ?>"
         style="position:relative;margin-bottom:20px;animation:fadeUp 0.4s ease <?= $i*0.06 ?>s both">
      <!-- dot -->
      <div style="position:absolute;left:-22px;top:20px;width:12px;height:12px;border-radius:50%;
                  background:<?= $cfg['color'] ?>;border:2px solid var(--bg-primary);
                  box-shadow:0 0 0 3px <?= $cfg['border'] ?>"></div>

      <div class="card" style="border-left:3px solid <?= $cfg['color'] ?>;margin-bottom:0">
        <!-- header row -->
        <div style="display:flex;align-items:flex-start;justify-content:space-between;gap:10px;margin-bottom:10px;flex-wrap:wrap">
          <div style="display:flex;align-items:center;gap:8px;flex-wrap:wrap">
            <span style="font-size:18px"><?= $cfg['icon'] ?></span>
            <div>
              <div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap;margin-bottom:4px">
                <span style="font-family:monospace;font-size:12px;font-weight:700;
                             background:<?= $cfg['bg'] ?>;color:<?= $cfg['color'] ?>;
                             border:1px solid <?= $cfg['border'] ?>;padding:2px 8px;border-radius:6px">
                  v<?= htmlspecialchars($u['version']) ?>
                </span>
                <span style="font-size:11px;font-weight:600;
                             background:<?= $cfg['bg'] ?>;color:<?= $cfg['color'] ?>;
                             border:1px solid <?= $cfg['border'] ?>;padding:2px 7px;border-radius:6px">
                  <?= $cfg['label'] ?>
                </span>
                <?php if($isFirst): ?>
                <span style="font-size:10px;font-weight:700;background:linear-gradient(135deg,#6366f1,#8b5cf6);color:#fff;padding:2px 8px;border-radius:6px;animation:pulse 2s infinite">LATEST</span>
                <?php endif; ?>
              </div>
              <div style="font-size:15px;font-weight:700;color:var(--text-primary)"><?= htmlspecialchars($u['title']) ?></div>
            </div>
          </div>
          <div style="font-size:12px;color:var(--text-muted);flex-shrink:0;white-space:nowrap">
            <?= date('M j, Y', strtotime($u['created_at'])) ?>
          </div>
        </div>

        <!-- bullet points -->
        <?php if($lines): ?>
        <ul style="list-style:none;padding:0;margin:0;display:flex;flex-direction:column;gap:6px">
          <?php foreach($lines as $line): ?>
          <li style="display:flex;align-items:flex-start;gap:8px;font-size:13px;color:var(--text-secondary);line-height:1.6">
            <span style="width:18px;height:18px;border-radius:5px;background:<?= $cfg['bg'] ?>;
                         border:1px solid <?= $cfg['border'] ?>;display:flex;align-items:center;
                         justify-content:center;flex-shrink:0;margin-top:2px">
              <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="<?= $cfg['color'] ?>" stroke-width="3.5"><polyline points="20 6 9 17 4 12"/></svg>
            </span>
            <?= htmlspecialchars($line) ?>
          </li>
          <?php endforeach; ?>
        </ul>
        <?php endif; ?>
      </div>
    </div>
    <?php endforeach; ?>
  </div>

  <?php else: ?>
  <div class="card" style="text-align:center;padding:48px 24px">
    <div style="font-size:48px;margin-bottom:12px">🆕</div>
    <div style="font-size:16px;font-weight:600;color:var(--text-primary);margin-bottom:6px">No updates yet</div>
    <div style="font-size:13px;color:var(--text-muted)">Check back soon for new features and improvements.</div>
  </div>
  <?php endif; ?>

</div><!-- /tab-updates -->

<!-- ══ TAB: APPEARANCE ════════════════════════════════════════════════ -->
<div id="tab-appearance" class="st-tab-content" style="display:none">
  <div class="card" style="max-width:520px">
    <div style="font-size:15px;font-weight:700;color:var(--text-primary);margin-bottom:18px;display:flex;align-items:center;gap:8px">
      🌗 Theme
    </div>

    <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px" id="themeOptions">
      <!-- Dark -->
      <div class="theme-opt" data-theme="dark" onclick="setTheme('dark')"
           style="padding:16px;border-radius:12px;border:2px solid var(--accent);cursor:pointer;
                  background:rgba(99,102,241,0.06);transition:all 0.2s;text-align:center">
        <div style="font-size:28px;margin-bottom:8px">🌙</div>
        <div style="font-size:13px;font-weight:700;color:var(--text-primary)">Dark</div>
        <div style="font-size:11px;color:var(--text-muted);margin-top:2px">Easy on the eyes</div>
        <div id="darkCheck" style="margin-top:8px;font-size:11px;color:var(--accent);font-weight:600">✓ Active</div>
      </div>
      <!-- Light -->
      <div class="theme-opt" data-theme="light" onclick="setTheme('light')"
           style="padding:16px;border-radius:12px;border:1px solid var(--border);cursor:pointer;
                  background:transparent;transition:all 0.2s;text-align:center">
        <div style="font-size:28px;margin-bottom:8px">☀️</div>
        <div style="font-size:13px;font-weight:700;color:var(--text-primary)">Light</div>
        <div style="font-size:11px;color:var(--text-muted);margin-top:2px">Classic look</div>
        <div id="lightCheck" style="margin-top:8px;font-size:11px;color:transparent;font-weight:600">✓ Active</div>
      </div>
    </div>

    <div style="margin-top:20px;padding-top:16px;border-top:1px solid var(--border)">
      <div style="font-size:13px;color:var(--text-muted)">
        💡 Theme preference is saved in your browser and applies across all pages.
      </div>
    </div>
  </div>
</div><!-- /tab-appearance -->

<!-- ══ TAB: ACCOUNT ═══════════════════════════════════════════════════ -->
<div id="tab-account" class="st-tab-content" style="display:none">
  <div style="display:grid;gap:14px;max-width:580px">

    <!-- Account info card -->
    <div class="card">
      <div style="font-size:15px;font-weight:700;color:var(--text-primary);margin-bottom:16px">👤 Account Info</div>
      <div style="display:flex;flex-direction:column;gap:10px">
        <div style="display:flex;justify-content:space-between;align-items:center;padding:10px 14px;
                    background:var(--bg-secondary);border-radius:10px;border:1px solid var(--border)">
          <span style="font-size:13px;color:var(--text-muted)">Name</span>
          <span style="font-size:13px;font-weight:600;color:var(--text-primary)"><?= htmlspecialchars($user['name']) ?></span>
        </div>
        <div style="display:flex;justify-content:space-between;align-items:center;padding:10px 14px;
                    background:var(--bg-secondary);border-radius:10px;border:1px solid var(--border)">
          <span style="font-size:13px;color:var(--text-muted)">Email</span>
          <span style="font-size:13px;font-weight:600;color:var(--text-primary)"><?= htmlspecialchars($user['email']) ?></span>
        </div>
        <div style="display:flex;justify-content:space-between;align-items:center;padding:10px 14px;
                    background:var(--bg-secondary);border-radius:10px;border:1px solid var(--border)">
          <span style="font-size:13px;color:var(--text-muted)">Member since</span>
          <span style="font-size:13px;font-weight:600;color:var(--text-primary)"><?= date('F Y', strtotime($user['created_at'])) ?></span>
        </div>
        <?php if(!empty($user['auth_provider'])): ?>
        <div style="display:flex;justify-content:space-between;align-items:center;padding:10px 14px;
                    background:var(--bg-secondary);border-radius:10px;border:1px solid var(--border)">
          <span style="font-size:13px;color:var(--text-muted)">Login method</span>
          <span style="font-size:13px;font-weight:600;color:var(--text-primary)"><?= ucfirst($user['auth_provider']) ?> <?= $user['auth_provider']==='google'?'🔵':'🔵' ?></span>
        </div>
        <?php endif; ?>
      </div>
    </div>

    <!-- Quick links card -->
    <div class="card">
      <div style="font-size:15px;font-weight:700;color:var(--text-primary);margin-bottom:14px">🔗 Quick Links</div>
      <div style="display:flex;flex-direction:column;gap:8px">
        <?php
        $links = [
          ['href'=>$siteUrl.'/profile.php',  'icon'=>'✏️', 'label'=>'Edit Profile & Change Password'],
          ['href'=>$siteUrl.'/reminders.php','icon'=>'⏰', 'label'=>'Manage Reminders'],
          ['href'=>$siteUrl.'/notifications.php','icon'=>'🔔','label'=>'View Notifications'],
          ['href'=>$siteUrl.'/contact.php',  'icon'=>'💬', 'label'=>'Contact & Support'],
        ];
        foreach($links as $lk): ?>
        <a href="<?= $lk['href'] ?>"
           style="display:flex;align-items:center;gap:10px;padding:11px 14px;border-radius:10px;
                  background:var(--bg-secondary);border:1px solid var(--border);
                  text-decoration:none;color:var(--text-primary);font-size:13px;font-weight:500;
                  transition:all 0.2s"
           onmouseover="this.style.borderColor='var(--accent)';this.style.background='rgba(99,102,241,0.06)'"
           onmouseout="this.style.borderColor='var(--border)';this.style.background='var(--bg-secondary)'">
          <span><?= $lk['icon'] ?></span>
          <?= htmlspecialchars($lk['label']) ?>
          <svg style="margin-left:auto;opacity:0.4" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="9 18 15 12 9 6"/></svg>
        </a>
        <?php endforeach; ?>
      </div>
    </div>

    <!-- Danger zone -->
    <div class="card" style="border-color:rgba(239,68,68,0.2)">
      <div style="font-size:15px;font-weight:700;color:var(--danger);margin-bottom:14px">⚠️ Danger Zone</div>
      <div style="display:flex;gap:10px;flex-wrap:wrap">
        <a href="<?= $siteUrl ?>/logout.php"
           style="display:inline-flex;align-items:center;gap:6px;padding:10px 18px;border-radius:10px;
                  background:rgba(100,116,139,0.1);border:1px solid rgba(100,116,139,0.25);
                  color:var(--text-secondary);text-decoration:none;font-size:13px;font-weight:600">
          🚪 Log Out
        </a>
        <a href="<?= $siteUrl ?>/delete-account.php"
           style="display:inline-flex;align-items:center;gap:6px;padding:10px 18px;border-radius:10px;
                  background:rgba(239,68,68,0.08);border:1px solid rgba(239,68,68,0.25);
                  color:var(--danger);text-decoration:none;font-size:13px;font-weight:600">
          🗑️ Delete Account
        </a>
      </div>
    </div>

  </div>
</div><!-- /tab-account -->

<!-- ══ DOWNLOAD OVERLAY ══════════════════════════════════════════════ -->
<div id="dlOverlay" style="
  display:none;position:fixed;inset:0;z-index:99999;
  background:rgba(0,0,0,0.6);backdrop-filter:blur(6px);
  align-items:center;justify-content:center">

  <!-- Download progress card -->
  <div id="dlCard" style="
    background:var(--bg-card);border:1px solid var(--border);
    border-radius:20px;padding:32px 36px;min-width:320px;max-width:400px;
    text-align:center;box-shadow:0 24px 60px rgba(0,0,0,0.4);
    animation:popIn 0.35s cubic-bezier(0.34,1.56,0.64,1) both">

    <!-- Icon area -->
    <div id="dlIconWrap" style="
      width:72px;height:72px;border-radius:20px;margin:0 auto 20px;
      background:linear-gradient(135deg,rgba(99,102,241,0.15),rgba(139,92,246,0.15));
      border:1px solid rgba(99,102,241,0.3);
      display:flex;align-items:center;justify-content:center;
      font-size:32px;transition:all 0.4s">
      ⬇️
    </div>

    <div id="dlTitle" style="font-size:17px;font-weight:800;color:var(--text-primary);margin-bottom:6px">
      Preparing Changelog...
    </div>
    <div id="dlSub" style="font-size:13px;color:var(--text-muted);margin-bottom:22px">
      Getting everything ready for you
    </div>

    <!-- Progress bar -->
    <div style="background:var(--bg-secondary);border-radius:8px;height:6px;overflow:hidden;margin-bottom:10px">
      <div id="dlBar" style="height:100%;width:0%;border-radius:8px;
           background:linear-gradient(90deg,#6366f1,#8b5cf6);
           transition:width 0.4s ease;box-shadow:0 0 8px rgba(99,102,241,0.5)"></div>
    </div>
    <div id="dlPct" style="font-size:12px;color:var(--text-muted);font-weight:600">0%</div>

  </div>

  <!-- Success card (hidden initially) -->
  <div id="dlSuccess" style="
    display:none;
    background:var(--bg-card);border:1px solid rgba(16,185,129,0.3);
    border-radius:20px;padding:36px 40px;min-width:320px;max-width:400px;
    text-align:center;box-shadow:0 24px 60px rgba(0,0,0,0.4);
    animation:popIn 0.4s cubic-bezier(0.34,1.56,0.64,1) both">

    <!-- Checkmark circle -->
    <div style="
      width:80px;height:80px;border-radius:50%;margin:0 auto 20px;
      background:linear-gradient(135deg,#10b981,#059669);
      display:flex;align-items:center;justify-content:center;
      box-shadow:0 8px 24px rgba(16,185,129,0.4);
      animation:bounceIn 0.5s cubic-bezier(0.34,1.56,0.64,1) both">
      <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
        <polyline points="20 6 9 17 4 12"/>
      </svg>
    </div>

    <div style="font-size:22px;font-weight:900;color:var(--text-primary);margin-bottom:8px">
      All set, let's go! 🎉
    </div>
    <div style="font-size:14px;color:var(--text-muted);margin-bottom:28px;line-height:1.6">
      Changelog downloaded successfully.<br>Taking you back to the dashboard…
    </div>

    <!-- Progress bar for redirect countdown -->
    <div style="background:var(--bg-secondary);border-radius:8px;height:5px;overflow:hidden;margin-bottom:14px">
      <div id="redirectBar" style="height:100%;width:100%;border-radius:8px;
           background:linear-gradient(90deg,#10b981,#34d399);
           transition:width 2.5s linear"></div>
    </div>
    <div style="font-size:12px;color:var(--text-muted)">Redirecting in <span id="redirectCount">3</span>s…</div>

  </div>
</div>

<!-- ══ STYLES ═════════════════════════════════════════════════════════ -->
<style>
@keyframes fadeUp   { from{opacity:0;transform:translateY(14px)} to{opacity:1;transform:translateY(0)} }
@keyframes pulse    { 0%,100%{opacity:1} 50%{opacity:0.6} }
@keyframes popIn    { from{opacity:0;transform:scale(0.85)} to{opacity:1;transform:scale(1)} }
@keyframes bounceIn { from{opacity:0;transform:scale(0.5)} to{opacity:1;transform:scale(1)} }
@keyframes spin     { to{transform:rotate(360deg)} }
</style>

<!-- ══ SCRIPTS ════════════════════════════════════════════════════════ -->
<script>
var SITE_URL = '<?= $siteUrl ?>';

// ── Download with animation ──────────────────────────────────────────────
function startDownload() {
  var overlay = document.getElementById('dlOverlay');
  var card    = document.getElementById('dlCard');
  var bar     = document.getElementById('dlBar');
  var pct     = document.getElementById('dlPct');
  var title   = document.getElementById('dlTitle');
  var sub     = document.getElementById('dlSub');
  var iconW   = document.getElementById('dlIconWrap');

  // Show overlay
  overlay.style.display = 'flex';

  // Animate progress bar in steps
  var steps = [
    {w:15,  t:'Preparing Changelog…',  s:'Collecting all updates',    p:'15%',  delay:0},
    {w:40,  t:'Gathering updates…',     s:'Organizing by version',     p:'40%',  delay:500},
    {w:70,  t:'Almost ready…',          s:'Formatting the changelog',  p:'70%',  delay:1100},
    {w:95,  t:'Finishing up…',          s:'Packaging everything',       p:'95%',  delay:1800},
  ];

  steps.forEach(function(step) {
    setTimeout(function() {
      bar.style.width = step.w + '%';
      title.textContent = step.t;
      sub.textContent   = step.s;
      pct.textContent   = step.p;
    }, step.delay);
  });

  // Trigger actual file download after short delay
  setTimeout(function() {
    var a = document.createElement('a');
    a.href = SITE_URL + '/settings.php?download=changelog';
    a.download = 'studytrack-changelog.txt';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  }, 1200);

  // Show success popup
  setTimeout(function() {
    bar.style.width = '100%';
    pct.textContent = '100%';

    setTimeout(function() {
      // Swap to success card
      card.style.display = 'none';
      var success = document.getElementById('dlSuccess');
      success.style.display = 'block';

      // Start redirect bar animation
      setTimeout(function() {
        document.getElementById('redirectBar').style.width = '0%';
      }, 50);

      // Countdown
      var secs = 3;
      var countEl = document.getElementById('redirectCount');
      var timer = setInterval(function() {
        secs--;
        if (countEl) countEl.textContent = secs;
        if (secs <= 0) {
          clearInterval(timer);
          window.location.href = SITE_URL + '/dashboard.php';
        }
      }, 1000);

    }, 350);
  }, 2400);
}

// ── Tab switching ────────────────────────────────────────────────────────
function switchTab(name, btn) {
  document.querySelectorAll('.st-tab-content').forEach(function(t){ t.style.display='none'; });
  document.getElementById('tab-'+name).style.display='block';
  document.querySelectorAll('.st-tab').forEach(function(b){
    b.style.color='var(--text-secondary)';
    b.style.borderBottom='2px solid transparent';
  });
  btn.style.color='var(--accent)';
  btn.style.borderBottom='2px solid var(--accent)';
  try{ localStorage.setItem('settingsTab', name); }catch(e){}
}

// ── Restore last tab ─────────────────────────────────────────────────────
(function(){
  try{
    var last = localStorage.getItem('settingsTab');
    if(last){
      var btn = document.querySelector('[data-tab="'+last+'"]');
      if(btn) switchTab(last, btn);
    }
  }catch(e){}
})();

// ── Filter updates ───────────────────────────────────────────────────────
function filterUpdates(filter, btn) {
  document.querySelectorAll('.uf-chip').forEach(function(c){ c.style.opacity='0.55'; });
  btn.style.opacity='1';
  document.querySelectorAll('.upd-item').forEach(function(item){
    item.style.display = (filter==='all' || item.getAttribute('data-type')===filter) ? '' : 'none';
  });
}

// ── Theme switcher ───────────────────────────────────────────────────────
function setTheme(theme) {
  document.documentElement.setAttribute('data-theme', theme);
  try{ localStorage.setItem('stTheme', theme); }catch(e){}
  updateThemeUI(theme);
}
function updateThemeUI(theme) {
  document.querySelectorAll('.theme-opt').forEach(function(opt){
    var isActive = opt.getAttribute('data-theme') === theme;
    opt.style.border  = isActive ? '2px solid var(--accent)' : '1px solid var(--border)';
    opt.style.background = isActive ? 'rgba(99,102,241,0.08)' : 'transparent';
  });
  var dc = document.getElementById('darkCheck');
  var lc = document.getElementById('lightCheck');
  if(dc) dc.style.color = theme==='dark'  ? 'var(--accent)' : 'transparent';
  if(lc) lc.style.color = theme==='light' ? 'var(--accent)' : 'transparent';
}
(function(){
  var t = document.documentElement.getAttribute('data-theme') || 'dark';
  updateThemeUI(t);
})();
</script>

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