<?php
require_once __DIR__ . '/includes/config.php';
requireLogin();
$user        = currentUser();
$currentPage = 'pomodoro';
$pageTitle   = 'Pomodoro';

$today = date('Y-m-d');

$stDay = db()->prepare('SELECT COALESCE(SUM(minutes),0) as mins, COUNT(*) as sessions FROM study_sessions WHERE user_id=? AND session_date=?');
$stDay->execute([$user['id'], $today]);
$todayStats = $stDay->fetch();

$stWeek = db()->prepare('SELECT COALESCE(SUM(minutes),0) as mins FROM study_sessions WHERE user_id=? AND session_date >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)');
$stWeek->execute([$user['id']]);
$weekMins = (int)$stWeek->fetchColumn();

$stCyc = db()->prepare('SELECT COALESCE(SUM(cycles_completed),0) as c FROM pomodoro_sessions WHERE user_id=? AND started_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)');
$stCyc->execute([$user['id']]);
$weekCycles = (int)$stCyc->fetchColumn();

$stChart = db()->prepare('SELECT session_date, SUM(minutes) as mins FROM study_sessions WHERE user_id=? AND session_date >= DATE_SUB(CURDATE(), INTERVAL 6 DAY) GROUP BY session_date ORDER BY session_date');
$stChart->execute([$user['id']]);
$chartRaw = $stChart->fetchAll(PDO::FETCH_KEY_PAIR);
$chartData = [];
for ($i = 6; $i >= 0; $i--) {
    $d = date('Y-m-d', strtotime("-{$i} days"));
    $chartData[] = ['date' => date('D', strtotime($d)), 'mins' => (int)($chartRaw[$d] ?? 0)];
}

$stTasks = db()->prepare("SELECT id, title, subject FROM tasks WHERE user_id=? AND status != 'done' ORDER BY FIELD(priority,'urgent','high','medium','low') LIMIT 20");
$stTasks->execute([$user['id']]);
$linkedTasks = $stTasks->fetchAll();

$firstName = explode(' ', $user['full_name'])[0];
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Pomodoro – SPACE</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Barlow+Condensed:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&family=JetBrains+Mono:ital,wght@0,100..800;1,100..800&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/boxicons@2.1.4/css/boxicons.min.css">
<link rel="stylesheet" href="assets/css/main.css">
<meta name="csrf-token" content="<?= e(csrfToken()) ?>">
<style>
:root {
  --blue-acc:  #0ea5e9;
  --grn-acc:   #22c55e;
  --red-acc:   #ef4444;
  --amber-acc: #f59e0b;
}

.main-content {
  margin-left: var(--sidebar-w);
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  padding: 0;
}
@media (max-width: 768px) {
  .main-content {
    margin-left: 0;
    height: 100dvh;
  }
}

/* ═══════════════════════════════════════════════════════════
   MOBILE TOP HEADER
═══════════════════════════════════════════════════════════ */
.pomo-mob-header {
  display: none;
  flex-shrink: 0;
  padding: 13px 18px;
  align-items: center; justify-content: space-between;
  background: var(--bg);
  box-shadow: 0 2px 8px rgba(0,0,0,.05);
  z-index: 20;
}
@media (max-width: 768px) { .pomo-mob-header { display: flex; } }
.ih-btn {
  width: 40px; height: 40px; border-radius: 50%;
  background: var(--bg); box-shadow: var(--neu-sm);
  border: none; cursor: pointer; display: flex; align-items: center; justify-content: center;
  font-size: 20px; color: var(--text);
}
.ih-btn:active { box-shadow: var(--neu-in); }

/* ═══════════════════════════════════════════════════════════
   MAIN BODY LAYOUT
═══════════════════════════════════════════════════════════ */
.pomo-body {
  flex: 1; min-height: 0;
  display: flex; gap: 0; overflow: hidden;
}

.timer-pane {
  flex: 1; min-width: 0;
  display: flex; flex-direction: column;
  align-items: center; justify-content: space-between;
  padding: clamp(16px,2vh,28px) clamp(16px,3vw,32px);
  overflow: hidden;
}
@media (max-width: 768px) {
  .timer-pane { padding: 14px 18px 20px; }
}

.stats-pane {
  width: 280px; flex-shrink: 0;
  display: flex; flex-direction: column; gap: 12px;
  padding: clamp(16px,2vh,28px) 20px clamp(16px,2vh,28px) 0;
  overflow-y: auto;
  -ms-overflow-style: none; scrollbar-width: none;
}
.stats-pane::-webkit-scrollbar { display: none; }
@media (max-width: 900px) { .stats-pane { display: none; } }

/* ═══════════════════════════════════════════════════════════
   MODE CHIPS
═══════════════════════════════════════════════════════════ */
.mode-row {
  display: flex; gap: 8px; flex-shrink: 0;
  justify-content: center;
}
.mode-chip {
  padding: 8px 18px; border-radius: 50px;
  background: var(--bg); box-shadow: var(--neu-sm);
  border: none; cursor: pointer; font-family: 'Poppins', sans-serif;
  font-size: 12px; font-weight: 600; color: var(--muted);
  transition: .15s; display: flex; align-items: center; gap: 6px;
}
.mode-chip:active { box-shadow: var(--neu-in); }
.mode-chip.active { box-shadow: var(--neu-in); color: var(--text); }
.mode-chip i { font-size: 14px; }

/* ═══════════════════════════════════════════════════════════
   TIMER DISPLAY
═══════════════════════════════════════════════════════════ */
.timer-digits-wrap {
  flex: 1; display: flex; flex-direction: column;
  align-items: center; justify-content: center;
  gap: 0; position: relative;
}

.drag-hint {
  font-size: 10px; color: var(--muted); display: flex; align-items: center; gap: 4px;
  position: absolute; right: 0; top: 50%; transform: translateY(-50%);
  writing-mode: vertical-rl;
  opacity: .5;
}
.drag-hint i { font-size: 13px; transform: rotate(90deg); }

.timer-digit {
  font-family: 'Barlow Condensed', sans-serif;
  font-weight: 800;
  font-size: clamp(96px, 18vh, 160px);
  line-height: .88;
  color: var(--text);
  text-shadow: 5px 5px 12px rgba(0,0,0,.1), -3px -3px 6px rgba(255,255,255,.85);
  cursor: ns-resize;
  user-select: none;
  touch-action: none;
  transition: transform .1s, color .3s;
  letter-spacing: -4px;
}
.timer-digit:active { transform: scale(.97); }
.timer-digit.is-break { color: var(--grn-acc); }
.timer-digit.mode-long { color: var(--amber-acc); }

.timer-separator {
  font-family: 'Barlow Condensed', sans-serif;
  font-weight: 300;
  font-size: clamp(40px, 8vh, 70px);
  color: var(--muted); line-height: 1; margin: -4px 0; opacity: .6;
}

.timer-mode-label {
  font-size: clamp(9px,1.2vh,11px); font-weight: 700; text-transform: uppercase;
  letter-spacing: .14em; color: var(--muted);
  margin-top: 4px; transition: color .3s;
}

/* ═══════════════════════════════════════════════════════════
   CONTROLS - 3 BUTTONS LAYOUT
═══════════════════════════════════════════════════════════ */
.ctrl-row {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: clamp(20px, 6vw, 40px);
  width: 100%;
  margin-bottom: 2vh;
}

/* Play Button (Left) */
.ctrl-btn {
  width: 60px; height: 60px; border-radius: 50%; 
  background: var(--bg); border: none;
  box-shadow: var(--neu-out); display: flex; justify-content: center; align-items: center;
  cursor: pointer; color: var(--text); transition: box-shadow 0.2s, color 0.2s;
}
.ctrl-btn:active { box-shadow: var(--neu-in); }
.ctrl-btn svg { width: 26px; stroke-width: 2.5; }
.ctrl-btn.running { color: var(--red-acc); box-shadow: var(--neu-in); }

/* Mic Button (Center) */
.mic-wrapper {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.mic-btn-green {
  width: 100px; height: 100px; border-radius: 50%; 
  background: var(--bg); border: none;
  box-shadow: var(--neu-lg); display: flex; justify-content: center; align-items: center;
  cursor: pointer; color: var(--text); transition: all 0.2s; position: relative;
  -webkit-user-select: none; user-select: none; touch-action: manipulation;
  z-index: 2;
}
.mic-btn-green svg { width: 36px; stroke-width: 2; }

.mic-btn-green.recording {
  transform: scale(0.95);
  box-shadow: 0 2px 8px rgba(34, 197, 94, 0.4);
}
.mic-btn-green.recording::after {
  content: ''; position: absolute; top: -4px; left: -4px; right: -4px; bottom: -4px;
  border-radius: 50%; border: 3px solid var(--grn-acc);
  animation: pulse 1s infinite; z-index: 1;
}

@keyframes pulse {
  0% { transform: scale(1); opacity: 0.8; }
  100% { transform: scale(1.2); opacity: 0; }
}

.mic-label {
  position: absolute; bottom: -25px; left: 50%; transform: translateX(-50%);
  font-size: 11px; font-weight: 500; color: var(--text); white-space: nowrap;
}

/* Reset Button (Right) */
.reset-btn {
  width: 60px; height: 60px; border-radius: 50%; 
  background: var(--bg); border: none;
  box-shadow: var(--neu-out); display: flex; justify-content: center; align-items: center;
  cursor: pointer; color: var(--text); transition: box-shadow 0.2s, color 0.2s;
}
.reset-btn:active { box-shadow: var(--neu-in); }
.reset-btn svg { width: 26px; stroke-width: 2.5; }

/* Voice Status */
.voice-status {
  font-size: clamp(10px,1.3vh,12px); color: var(--muted); font-style: italic;
  text-align: center; height: 18px; flex-shrink: 0;
  transition: color .2s;
}
.voice-status.on { color: var(--blue-acc); font-style: normal; font-weight: 600; }

/* ═══════════════════════════════════════════════════════════
   STATS PANE
═══════════════════════════════════════════════════════════ */
.stat-card {
  background: var(--bg); border-radius: 20px;
  padding: 18px 16px; box-shadow: var(--neu-out);
}
.stat-card-title {
  font-size: 10px; font-weight: 700; text-transform: uppercase;
  letter-spacing: .08em; margin-bottom: 14px; color: var(--text);
  display: flex; align-items: center; gap: 6px;
}
.stat-card-title i { font-size: 14px; color: var(--muted); }

.stats-3 { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 8px; }
.stat-box {
  background: var(--bg); border-radius: 14px; padding: 12px 8px;
  box-shadow: var(--neu-sm); text-align: center;
}
.stat-box-val { font-size: 22px; font-weight: 300; line-height: 1; }
.stat-box-lbl { font-size: 8px; color: var(--muted); text-transform: uppercase; letter-spacing: .05em; margin-top: 3px; }

/* Bar Chart */
.bar-chart { display: flex; align-items: flex-end; gap: 4px; height: 50px; }
.bar-col { flex: 1; display: flex; flex-direction: column; align-items: center; gap: 3px; }
.bar-fill {
  width: 100%; border-radius: 4px 4px 0 0;
  background: var(--bg); box-shadow: var(--neu-in);
  transition: height .5s ease, background .3s;
  min-height: 3px;
}
.bar-fill.today { background: var(--blue-acc); box-shadow: 0 2px 6px rgba(14,165,233,.4); }
.bar-lbl { font-size: 8px; color: var(--muted); }

/* ═══════════════════════════════════════════════════════════
   SETTINGS
═══════════════════════════════════════════════════════════ */
.setting-row {
  display: flex; align-items: center; justify-content: space-between;
  padding: 8px 0; border-bottom: 1px solid rgba(0,0,0,.05);
}
.setting-row:last-child { border-bottom: none; }
.setting-lbl { font-size: 11px; font-weight: 600; color: var(--muted); }
.setting-val {
  width: 56px; padding: 5px 8px; border-radius: 8px;
  background: var(--bg); border: none; outline: none;
  box-shadow: var(--neu-in); font-family: 'Poppins', sans-serif;
  font-size: 12px; font-weight: 700; color: var(--text); text-align: center;
}
.sound-toggle {
  width: 42px; height: 22px; border-radius: 11px; position: relative;
  background: var(--bg); box-shadow: var(--neu-in);
  border: none; cursor: pointer; transition: .2s;
}
.sound-toggle::after {
  content: ''; position: absolute; top: 3px; left: 3px;
  width: 16px; height: 16px; border-radius: 50%;
  background: var(--muted); box-shadow: 2px 2px 4px var(--dark);
  transition: transform .2s, background .2s;
}
.sound-toggle.on::after { transform: translateX(20px); background: var(--grn-acc); }

/* ═══════════════════════════════════════════════════════════
   ALARM MODAL
═══════════════════════════════════════════════════════════ */
.alarm-backdrop {
  position: fixed; inset: 0;
  background: rgba(228,228,228,.7);
  backdrop-filter: blur(14px); -webkit-backdrop-filter: blur(14px);
  z-index: 600; display: flex; align-items: center; justify-content: center;
  padding: 20px;
  opacity: 0; pointer-events: none;
  transition: opacity .3s;
}
.alarm-backdrop.open { opacity: 1; pointer-events: all; }

.alarm-card {
  background: var(--bg); border-radius: 32px;
  box-shadow: var(--neu-lg);
  width: 100%; max-width: 340px;
  padding: 32px 28px;
  text-align: center;
  transform: scale(.9); transition: transform .3s;
}
.alarm-backdrop.open .alarm-card { transform: scale(1); }

.alarm-emoji { font-size: 52px; margin-bottom: 12px; animation: wobble 1s ease infinite; }
@keyframes wobble {
  0%,100%{transform:rotate(0)} 20%{transform:rotate(-8deg)} 40%{transform:rotate(8deg)}
  60%{transform:rotate(-4deg)} 80%{transform:rotate(4deg)}
}
.alarm-title { font-size: 22px; font-weight: 800; margin-bottom: 6px; }
.alarm-sub   { font-size: 13px; color: var(--muted); margin-bottom: 24px; line-height: 1.6; }
.alarm-stats { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 24px; }
.alarm-stat  {
  background: var(--bg); border-radius: 16px; padding: 14px 10px;
  box-shadow: var(--neu-sm); text-align: center;
}
.alarm-stat-val { font-size: 26px; font-weight: 300; }
.alarm-stat-lbl { font-size: 9px; color: var(--muted); text-transform: uppercase; letter-spacing: .05em; }
.alarm-btns { display: flex; gap: 10px; }
.alarm-btn {
  flex: 1; padding: 13px; border-radius: 50px; border: none; cursor: pointer;
  font-family: 'Poppins', sans-serif; font-size: 13px; font-weight: 700;
  background: var(--bg); box-shadow: var(--neu-sm); color: var(--text); transition: .15s;
  display: flex; align-items: center; justify-content: center; gap: 6px;
}
.alarm-btn:active { box-shadow: var(--neu-in); }
.alarm-btn.stop { background: var(--text); color: var(--bg); flex: 2; }
.alarm-btn i { font-size: 15px; }

.alarm-prog-wrap { margin-bottom: 20px; }
.alarm-prog-lbl { font-size: 10px; color: var(--muted); text-transform: uppercase; letter-spacing: .06em; margin-bottom: 6px; }
.alarm-prog-track { height: 8px; border-radius: 8px; background: var(--bg); box-shadow: var(--neu-in); overflow: hidden; }
.alarm-prog-fill { height: 100%; border-radius: 8px; background: var(--blue-acc); transition: width .4s; }
.alarm-prog-fill.break { background: var(--grn-acc); }
.alarm-prog-fill.long  { background: var(--amber-acc); }

.sound-wave {
  display: flex; align-items: center; justify-content: center; gap: 3px;
  height: 24px; margin-bottom: 8px;
}
.sw-bar {
  width: 4px; background: var(--blue-acc); border-radius: 2px;
  animation: wave 1s ease-in-out infinite;
}
.sw-bar:nth-child(1){height:8px;animation-delay:.0s}
.sw-bar:nth-child(2){height:16px;animation-delay:.1s}
.sw-bar:nth-child(3){height:22px;animation-delay:.2s}
.sw-bar:nth-child(4){height:16px;animation-delay:.3s}
.sw-bar:nth-child(5){height:8px;animation-delay:.4s}
@keyframes wave {
  0%,100%{transform:scaleY(1)} 50%{transform:scaleY(1.6)}
}

/* ═══════════════════════════════════════════════════════════
   SETTINGS SHEET
═══════════════════════════════════════════════════════════ */
.settings-backdrop {
  position: fixed; inset: 0;
  background: rgba(228,228,228,.6); backdrop-filter: blur(8px);
  z-index: 500; opacity: 0; pointer-events: none; transition: opacity .25s;
}
.settings-backdrop.open { opacity: 1; pointer-events: all; }
.settings-sheet {
  position: fixed; bottom: 0; left: 50%; transform: translate(-50%, 100%);
  width: 100%; max-width: 480px;
  background: var(--bg); border-radius: 28px 28px 0 0;
  box-shadow: 0 -8px 32px rgba(0,0,0,.1);
  z-index: 501; padding: 0 20px 32px;
  transition: transform .3s cubic-bezier(.25,.8,.25,1);
  -ms-overflow-style: none; scrollbar-width: none;
}
.settings-sheet::-webkit-scrollbar { display: none; }
.settings-sheet.open { transform: translate(-50%, 0); }
.sh-handle { width: 36px; height: 4px; background: var(--dark); border-radius: 2px; margin: 12px auto 18px; }
.sh-ttl { font-size: 16px; font-weight: 800; margin-bottom: 18px; }

.hidden { display: none !important; }
</style>
</head>
<body>
<div class="app-layout">
  <?php include __DIR__ . '/includes/sidebar.php'; ?>

  <main class="main-content" id="main">

    <!-- Mobile header -->
    <div class="pomo-mob-header">
      <button class="ih-btn" id="mob-menu-btn"><i class='bx bx-menu'></i></button>
      <div class="logo-circle-sm"><img src="assets/img/logo.svg" alt="S" width="26"></div>
      <button class="ih-btn" onclick="openSettings()"><i class='bx bx-cog'></i></button>
    </div>

    <div class="pomo-body">

      <!-- ═══════════ TIMER PANE ═══════════ -->
      <div class="timer-pane">

        <!-- Mode chips -->
        <div class="mode-row">
          <button class="mode-chip active" id="chip-work" onclick="setMode('work')">
            <i class='bx bx-brain'></i>Focus
          </button>
          <button class="mode-chip" id="chip-short" onclick="setMode('short')">
            <i class='bx bx-coffee'></i>Short Break
          </button>
          <button class="mode-chip" id="chip-long" onclick="setMode('long')">
            <i class='bx bx-walk'></i>Long Break
          </button>
        </div>

        <!-- Timer digits -->
        <div class="timer-digits-wrap">
          <div class="drag-hint">
            <i class='bx bx-transfer-alt'></i>
            <span>drag</span>
          </div>
          <div class="timer-digit" id="dig-min" data-type="min">25</div>
          <div class="timer-separator">:</div>
          <div class="timer-digit" id="dig-sec" data-type="sec">00</div>
          <div class="timer-mode-label" id="mode-lbl">FOCUS TIME</div>
        </div>

        <!-- Controls - 3 Buttons -->
        <div class="ctrl-row">
          
          <!-- Play Button (Left) -->
          <button class="ctrl-btn" id="play-btn" onclick="toggleTimer()" title="Play/Pause">
            <svg id="icon-play" viewBox="0 0 24 24" fill="none" stroke="currentColor" style="margin-left: 4px;">
              <polygon points="5 3 19 12 5 21 5 3"></polygon>
            </svg>
            <svg id="icon-pause" viewBox="0 0 24 24" fill="none" stroke="currentColor" style="display:none;">
              <rect x="6" y="4" width="4" height="16"></rect>
              <rect x="14" y="4" width="4" height="16"></rect>
            </svg>
          </button>

          <!-- Mic Button (Center) -->
          <div class="mic-wrapper">
            <button class="mic-btn-green" id="mic-btn">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"></path>
                <path d="M19 10v2a7 7 0 0 1-14 0v-2"></path>
                <line x1="12" y1="19" x2="12" y2="23"></line>
                <line x1="8" y1="23" x2="16" y2="23"></line>
              </svg>
            </button>
            <span class="mic-label">Hold to Speak</span>
          </div>

          <!-- Reset Button (Right) -->
          <button class="reset-btn" id="reset-btn" onclick="resetTimer()" title="Reset">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
              <path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"></path>
              <polyline points="3 3 3 8 8 8"></polyline>
            </svg>
          </button>

        </div>

        <!-- Voice status -->
        <div class="voice-status" id="voice-status">Try saying: "Set the timer to 10 minutes"</div>

      </div>
      <!-- /timer-pane -->

      <!-- ═══════════ STATS PANE ═══════════ -->
      <div class="stats-pane">

        <!-- Today stats -->
        <div class="stat-card">
          <div class="stat-card-title"><i class='bx bx-sun'></i>Today</div>
          <div class="stats-3">
            <div class="stat-box">
              <div class="stat-box-val" id="stat-hrs"><?= round($todayStats['mins']/60, 1) ?></div>
              <div class="stat-box-lbl">Hours</div>
            </div>
            <div class="stat-box">
              <div class="stat-box-val" id="stat-sess"><?= $todayStats['sessions'] ?></div>
              <div class="stat-box-lbl">Sessions</div>
            </div>
            <div class="stat-box">
              <div class="stat-box-val"><?= $weekCycles ?></div>
              <div class="stat-box-lbl">Wk Cycles</div>
            </div>
          </div>
        </div>

        <!-- 7-day chart -->
        <div class="stat-card">
          <div class="stat-card-title"><i class='bx bx-bar-chart-alt'></i>7-Day Focus</div>
          <?php
          $maxMins = max(1, max(array_column($chartData, 'mins')));
          ?>
          <div class="bar-chart" id="week-chart">
            <?php foreach ($chartData as $i => $day): ?>
              <div class="bar-col">
                <div class="bar-fill <?= $i===6 ? 'today' : '' ?>"
                     style="height:<?= round($day['mins']/$maxMins * 50) ?>px"
                     title="<?= $day['mins'] ?> min"></div>
                <div class="bar-lbl"><?= $day['date'] ?></div>
              </div>
            <?php endforeach; ?>
          </div>
          <div style="font-size:10px;color:var(--muted);margin-top:8px;text-align:right">
            <?= round($weekMins/60, 1) ?>h this week
          </div>
        </div>

        <!-- Settings -->
        <div class="stat-card">
          <div class="stat-card-title"><i class='bx bx-cog'></i>Settings</div>

          <div class="setting-row">
            <span class="setting-lbl">Focus (min)</span>
            <input type="number" class="setting-val" id="set-work" value="25" min="1" max="120" onchange="updateSettings()">
          </div>
          <div class="setting-row">
            <span class="setting-lbl">Short break</span>
            <input type="number" class="setting-val" id="set-short" value="5" min="1" max="30" onchange="updateSettings()">
          </div>
          <div class="setting-row">
            <span class="setting-lbl">Long break</span>
            <input type="number" class="setting-val" id="set-long" value="15" min="1" max="60" onchange="updateSettings()">
          </div>
          <div class="setting-row">
            <span class="setting-lbl">Auto-start breaks</span>
            <button class="sound-toggle on" id="tog-auto" onclick="toggleAuto()"></button>
          </div>
          <div class="setting-row" style="border:none">
            <span class="setting-lbl">Sound alarm</span>
            <button class="sound-toggle on" id="tog-sound" onclick="toggleSound()"></button>
          </div>
        </div>

      </div>
      <!-- /stats-pane -->

    </div>
    <!-- /pomo-body -->
  </main>
</div>

<!-- ═══════════════════════════════════════════════════════════
     ALARM MODAL
═══════════════════════════════════════════════════════════ -->
<div class="alarm-backdrop" id="alarm-backdrop">
  <div class="alarm-card">
    <div class="sound-wave" id="sound-wave">
      <div class="sw-bar"></div><div class="sw-bar"></div><div class="sw-bar"></div>
      <div class="sw-bar"></div><div class="sw-bar"></div>
    </div>
    <div class="alarm-emoji" id="alarm-emoji">🎉</div>
    <div class="alarm-title" id="alarm-title">Session Complete!</div>
    <div class="alarm-sub"  id="alarm-sub">Great work! Time for a break.</div>

    <div class="alarm-prog-wrap">
      <div class="alarm-prog-lbl" id="alarm-prog-lbl">Today's progress</div>
      <div class="alarm-prog-track">
        <div class="alarm-prog-fill" id="alarm-prog-fill" style="width:0%"></div>
      </div>
    </div>

    <div class="alarm-stats">
      <div class="alarm-stat">
        <div class="alarm-stat-val" id="alarm-mins">0</div>
        <div class="alarm-stat-lbl">Min focused</div>
      </div>
      <div class="alarm-stat">
        <div class="alarm-stat-val" id="alarm-cycles">0</div>
        <div class="alarm-stat-lbl">Cycles done</div>
      </div>
    </div>

    <div class="alarm-btns">
      <button class="alarm-btn" id="alarm-snooze" onclick="snoozeAlarm()">
        <i class='bx bx-time-five'></i>+5 min
      </button>
      <button class="alarm-btn stop" onclick="dismissAlarm()">
        <i class='bx bx-stop-circle'></i>Stop Alarm
      </button>
    </div>
  </div>
</div>

<!-- ═══════════════════════════════════════════════════════════
     MOBILE SETTINGS SHEET
═══════════════════════════════════════════════════════════ -->
<div class="settings-backdrop" id="set-back" onclick="closeSettings()"></div>
<div class="settings-sheet" id="set-sheet">
  <div class="sh-handle"></div>
  <div class="sh-ttl">Timer Settings</div>
  <div class="setting-row">
    <span class="setting-lbl">Focus duration (min)</span>
    <input type="number" class="setting-val" id="mob-set-work" value="25" min="1" max="120" onchange="updateSettingsMob()">
  </div>
  <div class="setting-row">
    <span class="setting-lbl">Short break (min)</span>
    <input type="number" class="setting-val" id="mob-set-short" value="5" min="1" max="30" onchange="updateSettingsMob()">
  </div>
  <div class="setting-row">
    <span class="setting-lbl">Long break (min)</span>
    <input type="number" class="setting-val" id="mob-set-long" value="15" min="1" max="60" onchange="updateSettingsMob()">
  </div>
  <div class="setting-row">
    <span class="setting-lbl">Auto-start breaks</span>
    <button class="sound-toggle on" id="mob-tog-auto" onclick="toggleAutoMob()"></button>
  </div>
  <div class="setting-row" style="border:none;padding-bottom:0">
    <span class="setting-lbl">Sound alarm</span>
    <button class="sound-toggle on" id="mob-tog-sound" onclick="toggleSoundMob()"></button>
  </div>
  <div style="margin-top:24px;display:flex;gap:10px;">
    <button onclick="closeSettings()" style="flex:1;padding:12px;border-radius:50px;background:var(--bg);box-shadow:var(--neu-sm);border:none;cursor:pointer;font-family:'Poppins',sans-serif;font-size:13px;font-weight:700;">Done</button>
  </div>
</div>

<script src="assets/js/app.js"></script>
<script>
// Access CSRF from global window object (set in app.js)
const CSRF = window.CSRF;

// Timer state
let workMins  = 25, shortMins = 5, longMins = 15;
let mode      = 'work';
let remaining = workMins * 60;
let totalSecs = workMins * 60;
let running   = false;
let interval  = null;
let cyclesDone = 0;
let sessionStart = null;
let todayFocusMins = <?= (int)$todayStats['mins'] ?>;

// Prefs
let autoStart    = true;
let soundEnabled = true;

// Alarm state
let alarmOsc     = null;
let alarmGain    = null;
let alarmCtx     = null;
let alarmLooping = false;

// Voice
let recognition  = null;

// DOM elements
const minBlock = document.getElementById('dig-min');
const secBlock = document.getElementById('dig-sec');
const playBtn = document.getElementById('play-btn');
const iconPlay = document.getElementById('icon-play');
const iconPause = document.getElementById('icon-pause');
const resetBtn = document.getElementById('reset-btn');
const micBtn = document.getElementById('mic-btn');
const voiceStatus = document.getElementById('voice-status');

// ═══════════════════════════════════════════════════════════
// DISPLAY
// ═══════════════════════════════════════════════════
function updateDisplay() {
  const m = Math.floor(remaining / 60);
  const s = remaining % 60;
  minBlock.textContent = String(m).padStart(2,'0');
  secBlock.textContent = String(s).padStart(2,'0');
  const mm = String(m).padStart(2,'0'), ss = String(s).padStart(2,'0');
  document.title = `${mm}:${ss} — ${mode==='work'?'Focus':mode==='short'?'Short Break':'Long Break'} | SPACE`;
}

function updateModeColors() {
  const labels = { work: 'FOCUS TIME', short: 'SHORT BREAK', long: 'LONG BREAK' };
  document.getElementById('mode-lbl').textContent = labels[mode];
  minBlock.className = `timer-digit${mode==='short'?' is-break':mode==='long'?' mode-long':''}`;
  secBlock.className = `timer-digit${mode==='short'?' is-break':mode==='long'?' mode-long':''}`;
}

function updatePlayBtn(isPlaying) {
  if (isPlaying) {
    iconPlay.style.display = 'none';
    iconPause.style.display = 'block';
    playBtn.classList.add('running');
  } else {
    iconPlay.style.display = 'block';
    iconPause.style.display = 'none';
    playBtn.classList.remove('running');
  }
}

// ═══════════════════════════════════════════════════════════
// MODE CONTROL
// ═══════════════════════════════════════════════════
function setMode(m, startImmediately = false) {
  if (running && !startImmediately) return;
  mode = m;
  totalSecs = (m==='work' ? workMins : m==='short' ? shortMins : longMins) * 60;
  remaining = totalSecs;
  clearInterval(interval);
  running = false;
  updateDisplay();
  updateModeColors();
  updatePlayBtn(false);

  ['work','short','long'].forEach(x => {
    document.getElementById('chip-'+x).classList.toggle('active', x===m);
  });

  if (startImmediately) {
    setTimeout(toggleTimer, 400);
  }
}

// ═══════════════════════════════════════════════════════════
// TIMER
// ═══════════════════════════════════════════════════
function toggleTimer() {
  if (running) {
    clearInterval(interval);
    running = false;
    updatePlayBtn(false);
  } else {
    if (!sessionStart) sessionStart = Date.now();
    running = true;
    updatePlayBtn(true);
    interval = setInterval(tick, 1000);
  }
}

function tick() {
  if (remaining <= 0) {
    clearInterval(interval);
    running = false;
    onTimerDone();
    return;
  }
  remaining--;
  updateDisplay();
}

function resetTimer() {
  clearInterval(interval);
  running = false;
  sessionStart = null;
  remaining = totalSecs;
  updateDisplay();
  updatePlayBtn(false);
}

// ═══════════════════════════════════════════════════════════
// ON TIMER COMPLETE
// ═══════════════════════════════════════════════════════════
async function onTimerDone() {
  updatePlayBtn(false);

  if (mode === 'work') {
    const focusMins = workMins;
    cyclesDone = Math.min(4, cyclesDone + 1);
    todayFocusMins += focusMins;

    await saveFocusTime(focusMins);
    await saveSession(focusMins);
    updateStatDisplay();

    showAlarm('work', focusMins);
    sessionStart = null;
  } else {
    showAlarm('break', 0);
    sessionStart = null;
  }
}

// ═══════════════════════════════════════════════════════════
// ALARM
// ═══════════════════════════════════════════════════
function showAlarm(type, focusMins) {
  const backdrop  = document.getElementById('alarm-backdrop');
  const emoji     = document.getElementById('alarm-emoji');
  const title     = document.getElementById('alarm-title');
  const sub       = document.getElementById('alarm-sub');
  const minsEl    = document.getElementById('alarm-mins');
  const cyclesEl  = document.getElementById('alarm-cycles');
  const progFillEl= document.getElementById('alarm-prog-fill');
  const snoozeBtn = document.getElementById('alarm-snooze');
  const swBars    = document.querySelectorAll('.sw-bar');

  if (type === 'work') {
    emoji.textContent    = '🎉';
    title.textContent    = 'Focus Session Complete!';
    sub.textContent      = `${focusMins} minute focus done! Time for a well-earned break.`;
    progFillEl.className = 'alarm-prog-fill';
    snoozeBtn.style.display = 'flex';
  } else {
    emoji.textContent    = '💪';
    title.textContent    = 'Break Over!';
    sub.textContent      = 'Ready to focus again? Let\'s keep the momentum going!';
    progFillEl.className = 'alarm-prog-fill break';
    snoozeBtn.style.display = 'none';
  }

  minsEl.textContent   = type === 'work' ? focusMins : '—';
  cyclesEl.textContent = cyclesDone;

  const goal = workMins * 4;
  const pct  = Math.min(100, Math.round(todayFocusMins / goal * 100));
  progFillEl.style.width = pct + '%';

  swBars.forEach(b => b.style.background = type==='work' ? '#0ea5e9' : '#22c55e');

  backdrop.classList.add('open');
  startAlarmSound(type);
}

function dismissAlarm() {
  document.getElementById('alarm-backdrop').classList.remove('open');
  stopAlarmSound();
  if (mode === 'work') {
    const nextMode = cyclesDone >= 4 ? 'long' : 'short';
    cyclesDone = cyclesDone >= 4 ? 0 : cyclesDone;
    setMode(nextMode, autoStart);
  } else {
    setMode('work', autoStart);
  }
}

function snoozeAlarm() {
  document.getElementById('alarm-backdrop').classList.remove('open');
  stopAlarmSound();
  remaining = 5 * 60;
  totalSecs = remaining;
  toggleTimer();
}

// ═══════════════════════════════════════════════════════════
// ALARM SOUND
// ═══════════════════════════════════════════════════
function startAlarmSound(type) {
  if (!soundEnabled) return;
  stopAlarmSound();
  alarmLooping = true;
  playChime(type);
}

function playChime(type) {
  if (!alarmLooping || !soundEnabled) return;
  try {
    alarmCtx = new (window.AudioContext || window.webkitAudioContext)();
    const notes  = type==='work' ? [523,659,784,1047] : [784,659,523,440];
    const timings= [0, 0.22, 0.44, 0.66];
    timings.forEach((t, i) => {
      const osc  = alarmCtx.createOscillator();
      const gain = alarmCtx.createGain();
      osc.connect(gain); gain.connect(alarmCtx.destination);
      osc.type      = 'sine';
      osc.frequency.value = notes[i];
      gain.gain.setValueAtTime(0, alarmCtx.currentTime + t);
      gain.gain.linearRampToValueAtTime(0.28, alarmCtx.currentTime + t + 0.05);
      gain.gain.exponentialRampToValueAtTime(0.001, alarmCtx.currentTime + t + 0.35);
      osc.start(alarmCtx.currentTime + t);
      osc.stop(alarmCtx.currentTime  + t + 0.4);
    });
    if (alarmLooping) {
      setTimeout(() => { if (alarmLooping) playChime(type); }, 2500);
    }
  } catch(e) {}
}

function stopAlarmSound() {
  alarmLooping = false;
  try { if (alarmCtx) { alarmCtx.close(); alarmCtx = null; } } catch(e) {}
}

// ═══════════════════════════════════════════════════════════
// DRAG TO SET TIME
// ═══════════════════════════════════════════════════
function makeDraggable(el) {
  let startY = 0, startVal = 0, isDragging = false;
  const type = el.dataset.type;
  const SENS = 14;

  function onStart(e) {
    if (running) return;
    isDragging = true;
    startY     = e.touches ? e.touches[0].clientY : e.clientY;
    startVal   = type === 'min'
      ? Math.floor(remaining / 60)
      : remaining % 60;
  }
  function onMove(e) {
    if (!isDragging) return;
    e.preventDefault();
    const y     = e.touches ? e.touches[0].clientY : e.clientY;
    const delta = startY - y;
    const ticks = Math.floor(delta / SENS);
    if (type === 'min') {
      let m = Math.min(99, Math.max(0, startVal + ticks));
      remaining = m * 60 + (remaining % 60);
    } else {
      let s = Math.min(59, Math.max(0, startVal + ticks));
      remaining = Math.floor(remaining / 60) * 60 + s;
    }
    totalSecs = remaining;
    updateDisplay();
  }
  function onEnd() { isDragging = false; }

  el.addEventListener('mousedown',   onStart);
  el.addEventListener('touchstart',  onStart, {passive:false});
  document.addEventListener('mousemove',  onMove);
  document.addEventListener('touchmove',  onMove, {passive:false});
  document.addEventListener('mouseup',    onEnd);
  document.addEventListener('touchend',   onEnd);
}

makeDraggable(minBlock);
makeDraggable(secBlock);

// ═══════════════════════════════════════════════════════════
// SETTINGS
// ═══════════════════════════════════════════════════
function updateSettings() {
  workMins  = Math.max(1, parseInt(document.getElementById('set-work').value)  || 25);
  shortMins = Math.max(1, parseInt(document.getElementById('set-short').value) || 5);
  longMins  = Math.max(1, parseInt(document.getElementById('set-long').value)  || 15);
  if (!running) { 
    totalSecs = (mode==='work'?workMins:mode==='short'?shortMins:longMins)*60; 
    remaining=totalSecs; 
    updateDisplay(); 
  }
  document.getElementById('mob-set-work').value  = workMins;
  document.getElementById('mob-set-short').value = shortMins;
  document.getElementById('mob-set-long').value  = longMins;
}
function updateSettingsMob() {
  document.getElementById('set-work').value  = document.getElementById('mob-set-work').value;
  document.getElementById('set-short').value = document.getElementById('mob-set-short').value;
  document.getElementById('set-long').value  = document.getElementById('mob-set-long').value;
  updateSettings();
}
function toggleAuto() {
  autoStart = !autoStart;
  document.getElementById('tog-auto').classList.toggle('on', autoStart);
  document.getElementById('mob-tog-auto').classList.toggle('on', autoStart);
}
function toggleSound() {
  soundEnabled = !soundEnabled;
  document.getElementById('tog-sound').classList.toggle('on', soundEnabled);
  document.getElementById('mob-tog-sound').classList.toggle('on', soundEnabled);
}
function toggleAutoMob()  { toggleAuto(); }
function toggleSoundMob() { toggleSound(); }

function openSettings()  { document.getElementById('set-back').classList.add('open');  document.getElementById('set-sheet').classList.add('open'); }
function closeSettings() { document.getElementById('set-back').classList.remove('open'); document.getElementById('set-sheet').classList.remove('open'); }

// ═══════════════════════════════════════════════════
// VOICE RECOGNITION
// ═══════════════════════════════════════════════════
const SpeechRecog = window.SpeechRecognition || window.webkitSpeechRecognition;
if (SpeechRecog) {
  recognition = new SpeechRecog();
  recognition.continuous   = false;
  recognition.interimResults = false;
  recognition.lang = 'en-US';

  recognition.onstart = () => {
    micBtn.classList.add('recording');
    voiceStatus.textContent = "Listening...";
    voiceStatus.classList.add('on');
  };
  recognition.onend = () => {
    micBtn.classList.remove('recording');
    voiceStatus.classList.remove('on');
    voiceStatus.textContent = 'Try saying: "Set the timer to 10 minutes"';
  };
  recognition.onerror = (e) => {
    voiceStatus.textContent = "Didn't catch that. Try again.";
    micBtn.classList.remove('recording');
  };
  recognition.onresult = (e) => {
    const txt = e.results[0][0].transcript.toLowerCase();
    voiceStatus.textContent = `Heard: "${txt}"`;
    voiceStatus.classList.add('on');
    parseVoiceCmd(txt);
    setTimeout(() => {
      voiceStatus.classList.remove('on');
      voiceStatus.textContent = 'Try saying: "Set the timer to 10 minutes"';
    }, 3500);
  };
}

function startRecording(e) {
  if(e) e.preventDefault();
  if(!recognition) {
    voiceStatus.textContent = "Voice not supported in this browser.";
    return;
  }
  try { recognition.start(); } catch(err) {} 
}

function stopRecording(e) {
  if(e) e.preventDefault();
  if(recognition) {
    try { recognition.stop(); } catch(err) {}
  }
}

micBtn.addEventListener('mousedown', startRecording);
micBtn.addEventListener('mouseup', stopRecording);
micBtn.addEventListener('mouseleave', stopRecording); 
micBtn.addEventListener('touchstart', startRecording, {passive: false});
micBtn.addEventListener('touchend', stopRecording, {passive: false});

function parseVoiceCmd(txt) {
  let t = txt
    .replace(/\b(to|too|two)\b/g, '2')
    .replace(/\bfour\b/g, '4').replace(/\bone\b/g, '1')
    .replace(/\bhalf an hour\b/g, '30 minutes')
    .replace(/\ban hour\b/g, '60 minutes');

  // Commands
  if (/\b(start|begin|go|resume)\b/.test(t) && !/set/.test(t)) { if (!running) toggleTimer(); return; }
  if (/\b(pause|stop|hold)\b/.test(t))  { if (running)  toggleTimer(); return; }
  if (/\b(reset|restart)\b/.test(t))    { resetTimer(); return; }
  if (/\bfocus\b/.test(t))              { setMode('work'); return; }
  if (/\bshort\s*break\b/.test(t))      { setMode('short'); return; }
  if (/\blong\s*break\b/.test(t))       { setMode('long'); return; }

  // Parse time
  let m = 0, s = 0;
  const mM = t.match(/(\d+)\s*(min|minute|minutes)/);
  const sM = t.match(/(\d+)\s*(sec|second|seconds)/);
  if (mM) m = parseInt(mM[1]);
  if (sM) s = parseInt(sM[1]);
  if (!mM && !sM) {
    const nm = t.match(/(\d+)/);
    if (nm) m = parseInt(nm[1]);
  }
  if (m === 0 && s === 0) { 
    voiceStatus.textContent = "No time detected. Say '10 minutes'.";
    return; 
  }

  if (running) toggleTimer();
  remaining = Math.min(99,m) * 60 + Math.min(59,s);
  totalSecs = remaining;
  updateDisplay();
  voiceStatus.textContent = `Timer set for ${m}m ${s}s`;

  if (/\b(start|go|begin)\b/.test(t)) setTimeout(toggleTimer, 300);
}

// ═══════════════════════════════════════════════════════════
// DB SAVE
// ═══════════════════════════════════════════════════
async function saveFocusTime(minutes) {
  if (minutes < 1) return;
  await fetch('api/pomodoro.php?action=save_study', {
    method:'POST',
    headers:{'Content-Type':'application/json'},
    body: JSON.stringify({
      csrf_token: CSRF,
      subject: '',
      minutes,
    })
  });
}

async function saveSession(minutes) {
  await fetch('api/pomodoro.php?action=save_session', {
    method:'POST',
    headers:{'Content-Type':'application/json'},
    body: JSON.stringify({
      csrf_token: CSRF,
      subject:    '',
      task_id:    null,
      work_minutes:      workMins,
      break_minutes:     shortMins,
      cycles_completed:  cyclesDone,
      total_focus_minutes: minutes,
    })
  });
}

function updateStatDisplay() {
  const hrs  = (todayFocusMins / 60).toFixed(1);
  const sEl  = document.getElementById('stat-sess');
  const hEl  = document.getElementById('stat-hrs');
  if (hEl) hEl.textContent = hrs;
  if (sEl) sEl.textContent = parseInt(sEl.textContent||0) + 1;
}

// ═══════════════════════════════════════════════════════════
// MOBILE MENU
// ═══════════════════════════════════════════════════
document.getElementById('mob-menu-btn')?.addEventListener('click', () => {
  document.getElementById('side-menu')?.classList.add('active');
  document.getElementById('menu-overlay')?.classList.add('active');
});

// ═══════════════════════════════════════════════════════════
// INIT
// ═══════════════════════════════════════════════════
updateDisplay();
updateModeColors();
</script>
</body>
</html>