# ปฏิบัติการที่ 9: Pomodoro Timer App

## วัตถุประสงค์

สร้าง **Pomodoro Timer** - เทคนิคในการจัดการเวลา:

- 🔴 **Work**: ทำงาน 25 นาที
- 🟢 **Break**: พักผ่อน 5 นาที
- 🔄 **Repeat**: ทำซ้ำ 4 รอบ แล้วพักนาน 15 นาที

---

## Project Structure

```
lab09/pomodoro/
├── index.html      (HTML & CSS)
├── app.js          (JavaScript logic)
└── style.css       (Styling - optional)
```

---

## Step 1: สร้าง HTML

สร้างไฟล์ `index.html`:

```html
<!DOCTYPE html>
<html lang="th">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Pomodoro Timer</title>
  </head>
  <body>
    <div class="container">
      <h1>Pomodoro Timer</h1>
      <p class="subtitle">โฟกัสให้เต็มที่ 25 นาที!</p>

      <div class="timer-display work" id="timerDisplay">
        <div class="phase work" id="phase">Work</div>
        <div class="time" id="timeDisplay">25:00</div>
        <div class="sessions">Session <span id="currentSession">1</span>/4</div>
      </div>

      <div class="progress-container">
        <div class="progress-bar" id="progressBar"></div>
      </div>

      <div class="controls">
        <button class="btn-start" id="startBtn">▶️ เริ่ม</button>
        <button class="btn-reset" id="resetBtn">🔄 รีเซ็ต</button>
      </div>

      <div class="settings">
        <div class="settings-title">⚙️ ตั้งค่า</div>
        <div class="settings-grid">
          <div class="setting-item">
            <div class="setting-label">Work Time (นาที)</div>
            <input
              type="number"
              id="workTime"
              class="setting-input"
              value="25"
              min="1"
              max="60"
            />
          </div>
          <div class="setting-item">
            <div class="setting-label">Break Time (นาที)</div>
            <input
              type="number"
              id="breakTime"
              class="setting-input"
              value="5"
              min="1"
              max="30"
            />
          </div>
        </div>
      </div>

      <div class="stats">
        <div class="stat-item">
          <div class="stat-label">✅ Completed</div>
          <div class="stat-value" id="completedCount">0</div>
        </div>
        <div class="stat-item">
          <div class="stat-label">Total Time</div>
          <div class="stat-value" id="totalTime">0 min</div>
        </div>
      </div>
    </div>
  </body>
</html>
```

## Step 2: สร้าง CSS

สร้างไฟล์ `styles.css`:

```css
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
  background: linear-gradient(135deg, #eee 0%, #eee 100%);
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.container {
  background: white;
  border-radius: 20px;
  padding: 50px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  text-align: center;
  max-width: 500px;
  width: 100%;
}

h1 {
  color: #333;
  margin-bottom: 10px;
  font-size: 32px;
}

.subtitle {
  color: #999;
  margin-bottom: 30px;
  font-size: 16px;
}

.timer-display {
  background: linear-gradient(135deg, #123456 0%, #123456 100%);
  color: white;
  border-radius: 15px;
  padding: 40px;
  margin-bottom: 30px;
  box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
}

.phase {
  font-size: 20px;
  margin-bottom: 10px;
  text-transform: uppercase;
  letter-spacing: 2px;
  opacity: 0.8;
}

.phase.work {
  color: #ff6b6b;
}

.phase.break {
  color: #51cf66;
}

.time {
  font-size: 80px;
  font-weight: bold;
  font-family: "Courier New", monospace;
  letter-spacing: 5px;
  line-height: 1;
  margin: 20px 0;
}

.sessions {
  font-size: 14px;
  opacity: 0.8;
  margin-top: 10px;
}

/* Progress Bar */
.progress-container {
  background: #e0e0e0;
  border-radius: 10px;
  height: 8px;
  margin-bottom: 30px;
  overflow: hidden;
}

.progress-bar {
  background: linear-gradient(90deg, #ffff00 0%, #00ff00 100%);
  height: 100%;
  width: 100%;
  transition: width 0.3s ease;
}

/* Controls */
.controls {
  display: flex;
  gap: 15px;
  justify-content: center;
  margin-bottom: 25px;
  flex-wrap: wrap;
}

button {
  padding: 12px 30px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  font-weight: bold;
  transition: all 0.3s;
  text-transform: uppercase;
  letter-spacing: 1px;
}

.btn-start {
  background: #28a745;
  color: white;
  flex: 1;
  min-width: 120px;
}

.btn-start:hover {
  background: #218838;
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(40, 167, 69, 0.3);
}

.btn-start.running {
  background: #ff9800;
}

.btn-start.running:hover {
  background: #e68900;
}

.btn-reset {
  background: #dc3545;
  color: white;
  flex: 1;
  min-width: 120px;
}

.btn-reset:hover {
  background: #c82333;
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(220, 53, 69, 0.3);
}

.btn-reset:disabled {
  background: #ccc;
  cursor: not-allowed;
  transform: none;
}

/* Settings */
.settings {
  background: #f8f9fa;
  border-radius: 10px;
  padding: 20px;
  margin-top: 25px;
  border: 2px dashed #ddd;
}

.settings-title {
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
  font-size: 14px;
  text-transform: uppercase;
  letter-spacing: 1px;
}

.settings-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

.setting-item {
  background: white;
  padding: 12px;
  border-radius: 8px;
  border: 1px solid #ddd;
}

.setting-label {
  color: #666;
  font-size: 12px;
  margin-bottom: 5px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.setting-input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 16px;
  text-align: center;
  font-weight: bold;
}

.setting-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 5px rgba(102, 126, 234, 0.3);
}

/* Stats */
.stats {
  background: #f8f9fa;
  border-radius: 10px;
  padding: 15px;
  margin-top: 20px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
}

.stat-item {
  background: white;
  padding: 10px;
  border-radius: 8px;
  border-left: 4px solid #667eea;
}

.stat-label {
  color: #999;
  font-size: 12px;
  margin-bottom: 5px;
}

.stat-value {
  color: #667eea;
  font-size: 24px;
  font-weight: bold;
}

/* Animations */
@keyframes pulse {
  0%,
  100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
}

.timer-display.work {
  animation: pulse 2s infinite;
}

/* Responsive */
@media (max-width: 600px) {
  .container {
    padding: 30px 20px;
  }

  .time {
    font-size: 60px;
    letter-spacing: 3px;
  }

  .controls {
    flex-direction: column;
  }

  .btn-start,
  .btn-reset {
    width: 100%;
  }
}

.notification {
  position: fixed;
  top: 20px;
  right: 20px;
  background: #28a745;
  color: white;
  padding: 15px 25px;
  border-radius: 8px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
  animation: slideIn 0.3s ease;
  z-index: 1000;
}

@keyframes slideIn {
  from {
    transform: translateX(400px);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}
```

---

## Step 3: สร้าง JavaScript Logic

สร้างไฟล์ `app.js`:

```javascript
// ================================
// Pomodoro Timer App
// ================================

// 📊 State
let state = {
  isRunning: false,
  isWorkPhase: true,
  timeLeft: 25 * 60, // วินาที
  totalTime: 25 * 60,
  currentSession: 1,
  completedSessions: 0,
  intervalId: null,
  workDuration: 25 * 60,
  breakDuration: 5 * 60,
  longBreakDuration: 15 * 60,
};

// DOM Elements
const timeDisplay = document.getElementById("timeDisplay");
const startBtn = document.getElementById("startBtn");
const resetBtn = document.getElementById("resetBtn");
const progressBar = document.getElementById("progressBar");
const phaseDisplay = document.getElementById("phase");
const timerDisplay = document.getElementById("timerDisplay");
const currentSessionDisplay = document.getElementById("currentSession");
const workTimeInput = document.getElementById("workTime");
const breakTimeInput = document.getElementById("breakTime");
const completedCountDisplay = document.getElementById("completedCount");
const totalTimeDisplay = document.getElementById("totalTime");

// ================================
// 🔧 Helper Functions
// ================================

function formatTime(seconds) {
  const minutes = Math.floor(seconds / 60);
  const secs = seconds % 60;
  return `${String(minutes).padStart(2, "0")}:${String(secs).padStart(2, "0")}`;
}

function updateDisplay() {
  timeDisplay.textContent = formatTime(state.timeLeft);
  currentSessionDisplay.textContent = state.currentSession;

  // อัปเดต Progress Bar
  const progress = ((state.totalTime - state.timeLeft) / state.totalTime) * 100;
  progressBar.style.width = progress + "%";

  // อัปเดต Phase
  if (state.isWorkPhase) {
    phaseDisplay.textContent = "🔴 Work";
    phaseDisplay.className = "phase work";
    timerDisplay.classList.remove("break");
    timerDisplay.classList.add("work");
  } else {
    phaseDisplay.textContent = "🟢 Break";
    phaseDisplay.className = "phase break";
    timerDisplay.classList.remove("work");
    timerDisplay.classList.add("break");
  }

  // อัปเดต Button
  if (state.isRunning) {
    startBtn.textContent = "⏸️ หยุด";
    startBtn.classList.add("running");
  } else {
    startBtn.textContent = "▶️ เริ่ม";
    startBtn.classList.remove("running");
  }

  // อัปเดต Stats
  const totalMinutes = Math.floor(
    (state.completedSessions * state.workDuration) / 60,
  );
  totalTimeDisplay.textContent = totalMinutes + " min";
  completedCountDisplay.textContent = state.completedSessions;
}

function playNotification() {
  const audioContext = new (window.AudioContext || window.webkitAudioContext)();
  const oscillator = audioContext.createOscillator();
  const gainNode = audioContext.createGain();

  oscillator.connect(gainNode);
  gainNode.connect(audioContext.destination);

  if (state.isWorkPhase) {
    oscillator.frequency.value = 800;
  } else {
    oscillator.frequency.value = 1200;
  }

  oscillator.type = "sine";
  gainNode.gain.setValueAtTime(0.3, audioContext.currentTime);
  gainNode.gain.exponentialRampToValueAtTime(
    0.01,
    audioContext.currentTime + 0.5,
  );

  oscillator.start(audioContext.currentTime);
  oscillator.stop(audioContext.currentTime + 0.5);
}

function showNotification(message) {
  const notification = document.createElement("div");
  notification.className = "notification";
  notification.textContent = message;
  document.body.appendChild(notification);

  setTimeout(() => {
    notification.remove();
  }, 3000);
}

// ================================
// 🎬 Timer Functions
// ================================

function startTimer() {
  if (state.isRunning) {
    // Pause
    clearInterval(state.intervalId);
    state.isRunning = false;
  } else {
    // Start
    state.isRunning = true;

    state.intervalId = setInterval(() => {
      state.timeLeft--;

      // ✅ ถ้าหมดเวลา
      if (state.timeLeft <= 0) {
        clearInterval(state.intervalId);
        state.isRunning = false;

        playNotification();

        // Switch Phase
        if (state.isWorkPhase) {
          // หลังจบ Work
          state.completedSessions++;
          showNotification("✅ Work Complete! Time for Break!");

          // ตรวจสอบว่าเสร็จ 4 รอบหรือยัง
          if (state.currentSession % 4 === 0) {
            // Long Break
            state.breakDuration = state.longBreakDuration;
            showNotification("🎉 Long Break 15 minutes!");
          } else {
            state.breakDuration = parseInt(breakTimeInput.value) * 60;
          }

          state.isWorkPhase = false;
          state.timeLeft = state.breakDuration;
          state.totalTime = state.breakDuration;
        } else {
          // หลังจบ Break
          state.isWorkPhase = true;
          state.currentSession++;

          if (state.currentSession <= 4) {
            state.workDuration = parseInt(workTimeInput.value) * 60;
            state.timeLeft = state.workDuration;
            state.totalTime = state.workDuration;
            showNotification(`Session ${state.currentSession} Started!`);
          } else {
            // หมดครบ 4 รอบแล้ว
            state.currentSession = 1;
            state.workDuration = parseInt(workTimeInput.value) * 60;
            state.timeLeft = state.workDuration;
            state.totalTime = state.workDuration;
            showNotification("🎊 All sessions completed! Great job!");
          }
        }
      }

      updateDisplay();
    }, 1000);
  }

  updateDisplay();
}

function resetTimer() {
  clearInterval(state.intervalId);
  state.isRunning = false;
  state.isWorkPhase = true;
  state.currentSession = 1;
  state.workDuration = parseInt(workTimeInput.value) * 60;
  state.timeLeft = state.workDuration;
  state.totalTime = state.workDuration;

  updateDisplay();
  showNotification("🔄 Timer Reset!");
}

// ================================
// 🎬 Event Listeners
// ================================

startBtn.addEventListener("click", startTimer);
resetBtn.addEventListener("click", resetTimer);

workTimeInput.addEventListener("change", () => {
  if (!state.isRunning) {
    state.workDuration = parseInt(workTimeInput.value) * 60;
    if (state.isWorkPhase) {
      state.timeLeft = state.workDuration;
      state.totalTime = state.workDuration;
      updateDisplay();
    }
  }
});

breakTimeInput.addEventListener("change", () => {
  if (!state.isRunning) {
    state.breakDuration = parseInt(breakTimeInput.value) * 60;
    if (!state.isWorkPhase) {
      state.timeLeft = state.breakDuration;
      state.totalTime = state.breakDuration;
      updateDisplay();
    }
  }
});

// Initialize
updateDisplay();
```

---

## Run App

### 1 เปิด index.html ด้วย Live Server

ใน VS Code: `Alt + L` → `Alt + O`

### 2 ทดสอบ

```
[คลิก ▶️ เริ่ม]
Timer เริ่มนับลง 25:00 → 24:59 → ...
(หลังจาก 25 นาที)
🔊 เสียง + 🟢 Break Phase (5 นาที)
[คลิก ▶️ เริ่ม อีกครั้ง]
(ทำซ้ำ 4 รอบ)
🎉 Long Break 15 นาที
```

### 3 ตั้งค่า

- **Work Time**: เปลี่ยนจาก 25 เป็น 10 นาทีเพื่อทดสอบเร็ว
- **Break Time**: เปลี่ยนจาก 5 เป็น 2 นาที

---

## Code Explanation

### ส่วน async ที่สำคัญ

**1 setInterval - นับลงทุกๆ 1 วินาที**

```javascript
state.intervalId = setInterval(() => {
  state.timeLeft--; // ลดเวลา

  if (state.timeLeft <= 0) {
    // เมื่อหมดเวลา
    playNotification(); // เล่นเสียง
    // Switch phase
  }

  updateDisplay(); // อัปเดต UI
}, 1000);
```

**2 Phase Switching - สลับจาก Work ↔ Break**

```javascript
if (state.isWorkPhase) {
  // เพิ่มจำนวนที่เสร็จ
  state.completedSessions++;
  // Switch to Break
  state.isWorkPhase = false;
} else {
  // Switch back to Work
  state.isWorkPhase = true;
  state.currentSession++;
}
```

**3 Progress Bar Animation**

```javascript
const progress = ((state.totalTime - state.timeLeft) / state.totalTime) * 100;
progressBar.style.width = progress + "%";
// คำนวณเปอร์เซ็นต์ที่ทำเสร็จแล้ว
```

---

## Features ที่มี

| Feature                | รายละเอียด                        |
| ---------------------- | --------------------------------- |
| **Work Phase**         | นับลง 25 นาที (ปรับได้)           |
| 🟢 **Break Phase**     | นับลง 5 นาที (ปรับได้)            |
| 🎉 **Long Break**      | หลังจาก 4 รอบ = 15 นาที           |
| 🔊 **Sound Alert**     | เล่นเสียงต่างกันสำหรับ Work/Break |
| 📊 **Progress Bar**    | แสดงความคืบหน้า                   |
| 📈 **Stats**           | นับจำนวนที่เสร็จและเวลารวม        |
| ⚙️ **Custom Settings** | ปรับ Work/Break time ได้          |

---

## Testing Checklist

- [ ] Timer เริ่ม/หยุดได้
- [ ] Progress bar เคลื่อนไหว
- [ ] Phase สลับ Work → Break
- [ ] Notification แสดง
- [ ] Sound เล่นเมื่อจบ
- [ ] Stats อัปเดต
- [ ] Reset ทำงาน
- [ ] Settings เปลี่ยนค่าได้

---

## Enhancement Ideas

- [ ] **Sound Options** - เลือกเสียง alert
- [ ] **Themes** - Dark Mode, Light Mode
- [ ] **History** - บันทึกประวัติการใช้งาน
- [ ] **Notifications** - ใช้ Browser Notification API
- [ ] **Desktop App** - Package เป็น Electron app
- [ ] **Mobile App** - Progressive Web App (PWA)

---

## คำถามทดสอบความเข้าใจ (Assessment Questions)

### ส่วนที่ 1: ความเข้าใจเทคนิค Pomodoro

**คำถาม 1.1**
เทคนิค Pomodoro คืออะไร เหตุใดจึงเลือกใช้เวลา 25 นาที สำหรับการทำงาน

**คำถาม 1.2**
หากต้องการปรับเวลา Work/Break ให้แตกต่างจาก default (25/5) จะต้องแก้ไขโค้ดส่วนไหน

**คำถาม 1.3**
ทำไมหลังจาก 4 รอบ (pomodoros) จึงมี Long Break ขนาด 15 นาที ประโยชน์คืออะไร

---

### ส่วนที่ 2: การจัดโครงสร้าง State

**คำถาม 2.1**
ปัจจุบัน app เก็บ state อะไรบ้าง เช่น:

- เวลาที่เหลือ
- Phase (work/break)
- Rounds counter
- ...อื่นๆ

**คำถาม 2.2**
ทำไมจึงต้องมี `rounds` state หากแค่เก็บ `phase` ก็พอ

**คำถาม 2.3**
ถ้าต้องการให้ Pomodoro Count อัปเดต เมื่อจบแต่ละ Work phase จะแก้ไขฟังก์ชัน `completePhase()` ยังไง

---

### ส่วนที่ 3: Timer Logic

**คำถาม 3.1**
อธิบายการทำงานของ `setInterval()` ในส่วน timer - จะเกิดอะไรขึ้นทุก 1 วินาที

**คำถาม 3.2**
เหตุใดจึงต้องมี `timerInterval` เป็น global variable ถ้าไม่มี app จะเป็นยังไง

**คำถาม 3.3**
ถ้าผู้ใช้คลิก "เริ่ม" 2 ครั้งติดต่อกัน จะเกิดอะไรขึ้น มีวิธีแก้หรือไม่

---

### ส่วนที่ 4: DOM & UI

**คำถาม 4.1**
ฟังก์ชัน `updateDisplay()` ทำอะไร ต้องเรียกจากที่ไหนบ้าง

**คำถาม 4.2**
`formatTime()` ใช้ padding ด้วย `padStart(2, "0")` เพื่ออะไร ถ้าไม่มี timer จะแสดง 5:3 แทน 05:03 ได้หรือไม่

**คำถาม 4.3**
Progress bar คำนวณเปอร์เซ็นต์ยังไง เขียนสูตรออกมา

---

### ส่วนที่ 5: Events & Controls

**คำถาม 5.1**
ปุ่มควบคุมมีอะไรบ้าง (Start, Pause, Reset, Settings) แต่ละปุ่มเรียกฟังก์ชันไหน

**คำถาม 5.2**
ทำไม Pause ต้องหยุด timer ด้วย `clearInterval()` หากไม่ทำจะไปไป

**คำถาม 5.3**
Reset button ควรตั้งค่ากลับเป็นอะไร:

- `timeLeft`
- `phase`
- `rounds`
- `timerInterval`

---

### ส่วนที่ 6: Notifications & Sound

**คำถาม 6.1**
ฟังก์ชัน `playSound()` ใช้เทคนิคอะไรในการสร้างเสียง (Web Audio API? HTML Audio?)

**คำถาม 6.2**
ทำไม notification ควร work/break ต่างกันอย่างไร เสียง alarm ที่ดีควรเป็นยังไง

**คำถาม 6.3**
ถ้าต้องการเพิ่ม Desktop Notification ด้วย Browser Notification API จะแก้ไขฟังก์ชัน `completePhase()` ยังไง

---

### ส่วนที่ 7: Progress Tracking & Stats

**คำถาม 7.1**
Stats ต้องติดตามข้อมูลอะไร:

- Pomodoros ที่เสร็จแล้ว
- เวลารวมที่ทำงาน
- Long breaks ที่เกิดขึ้น

**คำถาม 7.2**
ตำแหน่งที่ดีที่สุดในการอัปเดต stats คือที่ไหน

**คำถาม 7.3**
วิธีการบันทึก stats ไว้ใน LocalStorage ได้อย่างไร

---

### ส่วนที่ 8: Bug Detection

**คำถาม 8.1**
ถ้า timer กำลังเดินอยู่ แล้วผู้ใช้เปิด DevTools ขนาดใหญ่ timer จะยังคงเดินต่อหรือไม่

**คำถาม 8.2**
ถ้า `completePhase()` เรียก ในขณะที่ timer ยังวิ่งอยู่ จะเกิด memory leak ได้หรือไม่

**คำถาม 8.3**
ใน mobile ถ้าผู้ใช้ล็อก screen ขณะ timer เดิน timer จะหยุดหรือยังคงเดิน วิธีแก้คืออะไร

---

### ส่วนที่ 9: Architecture & Code Quality

**คำถาม 9.1**
ถ้าต้องการแยก Timer logic ออกจาก UI ควรสร้าง class อย่างไร

**คำถาม 9.2**
Functions ที่มีมากควรจัดไว้ใน object เพื่อจัดการได้ดีขึ้นหรือไม่

**คำถาม 9.3**
Code reusability - ส่วนไหนของโค้ดสามารถทำให้เป็น utility functions ได้

---

### ส่วนที่ 10: Enhancements

**คำถาม 10.1**
วิธีเพิ่ม Dark Mode ควรแก้ไข CSS/JS ส่วนไหนบ้าง

**คำถาม 10.2**
วิธีบันทึกประวัติการใช้งาน (session history) คืออะไร

**คำถาม 10.3**
วิธีเพิ่ม Keyboard Shortcuts (Space = Start/Pause, R = Reset) ควรใช้ event ไหน

---

## เกณฑ์การประเมิน

| ระดับคะแนน    | เกณฑ์                                      |
| ------------- | ------------------------------------------ |
| **ผ่าน**      | ตอบคำถาม 1-5 ข้อ + app ทำงาน               |
| **ดี**        | ตอบ 7-10 ข้อ + เข้าใจ state management     |
| **ดีมาก**     | ตอบ 12-15 ข้อ + สามารถ enhance features    |
| **ยอดเยี่ยม** | ตอบ 18+ ข้อ + เข้าใจ architecture patterns |

---

## Learning Outcomes

เมื่อจบปฏิบัติการนี้ นิสิตควรเข้าใจ:

✅ เทคนิค Pomodoro และประโยชน์  
✅ State management ในแอปพลิเคชัน JavaScript  
✅ Timer mechanics ด้วย setInterval/clearInterval  
✅ DOM manipulation และ event handling  
✅ Progress tracking และ notifications  
✅ วิธีการ debug timing issues  
✅ Code architecture patterns  
✅ การปรับปรุงแอปด้วย features ใหม่
