// static/js/timer.js

// Play sounds
function playTimerAlert() {
  new Audio('/static/audio/timer_ping.mp3').play().catch(()=>{});
}
function playLogSound() {
  new Audio('/static/audio/log_ping.mp3').play().catch(()=>{});
}

// Compute ms until next 20‑min boundary
function msUntilNext20Min() {
  const now = new Date();
  const past = now.getMinutes() % 20;
  let delay = ((20 - past) % 20) * 60000
            - now.getSeconds() * 1000
            - now.getMilliseconds();
  if (delay < 0) delay += 20 * 60000;
  return delay;
}

// Console countdown (optional)
let countdownInterval = null;
function startCountdown(delay) {
  clearInterval(countdownInterval);
  const target = Date.now() + delay;
  countdownInterval = setInterval(() => {
    const rem = target - Date.now();
    if (rem <= 0) return clearInterval(countdownInterval);
    const m = Math.floor(rem / 60000),
          s = Math.floor((rem % 60000) / 1000);
    console.log(`Next chime in ${m}m ${s}s`);
  }, 1000);
}

// Schedule chime + re‑enable button
function scheduleChime() {
  const delay = msUntilNext20Min();
  startCountdown(delay);
  setTimeout(() => {
    playTimerAlert();
    const btn = document.getElementById('log-btn');
    if (btn) btn.disabled = false;
    scheduleChime();
  }, delay);
}

// Disable if already logged this block
function disableIfLoggedThisBlock() {
  const btn = document.getElementById('log-btn');
  if (!btn || !btn.dataset.lastLog) return;
  const last = new Date(btn.dataset.lastLog);
  const now  = new Date();
  const startMin = Math.floor(now.getMinutes() / 20) * 20;
  const blockStart = new Date(
    now.getFullYear(), now.getMonth(), now.getDate(),
    now.getHours(), startMin, 0, 0
  );
  if (last >= blockStart) btn.disabled = true;
}

// Update the progress bar DOM
function updateProgressBar(percent) {
  const bar = document.querySelector('.progress-bar');
  if (!bar) return;
  bar.style.width = percent + '%';
  bar.style.backgroundColor = percent >= 100 ? '#4CAF50' : '#2196F3';
}

// Update the Chart.js bar for the current hour
function updateChart() {
  if (!window.hourChart) return;
  const now = new Date().getHours();
  const idx = window.hourChart.data.labels.indexOf(`${now}:00`);
  if (idx >= 0) {
    window.hourChart.data.datasets[0].data[idx] += 1;
    window.hourChart.update();
  }
}

// Update the table cell for the current hour
function updateTable() {
  const table = document.querySelector('.data-table');
  if (!table) return;
  const now = new Date().getHours();
  const headers = Array.from(table.tHead.rows[0].cells);
  const idx = headers.findIndex(th => th.textContent === `${now}:00`);
  if (idx >= 0) {
    const cell = table.tBodies[0].rows[0].cells[idx];
    const val = parseInt(cell.textContent, 10) || 0;
    cell.textContent = val + 1;
  }
}

// Hook up the Log button
function setupLogButton() {
  const btn = document.getElementById('log-btn');
  if (!btn) return;
  btn.addEventListener('click', () => {
    playLogSound();
    btn.disabled = true;

    fetch('/log', { method: 'POST' })
      .then(resp => resp.json().then(body => ({ status: resp.status, body })))
      .then(({ status, body }) => {
        if (status >= 400) {
          alert(body.error || 'Cannot log now');
          return;
        }

        // 1) Left sidebar (monthly)
        document.getElementById('card-equity').textContent =
          parseFloat(body.monthly.equity).toFixed(2);
        document.getElementById('card-wc').textContent =
          parseFloat(body.monthly.working_capital).toFixed(2);
        document.getElementById('card-rev').textContent =
          parseFloat(body.monthly.monthly_revenue).toFixed(2);

        // 2) Right sidebar (weekly)
        document.getElementById('card-equity-2').textContent =
          parseFloat(body.weekly.equity).toFixed(2);
        document.getElementById('card-wc-2').textContent =
          parseFloat(body.weekly.working_capital).toFixed(2);
        document.getElementById('card-rev-2').textContent =
          parseFloat(body.weekly.weekly_revenue).toFixed(2);

        // 3) Progress bar
        updateProgressBar(body.percent);
        
       // 3.1) Update the “Total today” summary line
       const summary = document.querySelector('.summary');
       if (summary) {
         summary.textContent =
           `Total today: ${body.total_mins} minutes (${body.percent}% of 240‑min goal)`;
       }

        // 4) Chart & table
        updateChart();
        updateTable();

        // 5) Remember last-log timestamp
        btn.dataset.lastLog = body.timestamp || new Date().toISOString();
      })
      .catch(() => alert('Log failed'));
  });
}

// Clocks
function updateDigitalClock() {
  const el = document.getElementById('clock');
  if (el) el.textContent = new Date().toLocaleTimeString();
}
function updateAnalogClock() {
  const now = new Date();
  const secDeg = (now.getSeconds() / 60) * 360 - 90;
  const minDeg = (now.getMinutes() / 60) * 360 + (now.getSeconds() / 60) * 6 - 90;
  const hrDeg  = ((now.getHours() % 12) / 12) * 360 + (now.getMinutes() / 60) * 30 - 90;
  document.querySelector('.second-hand').style.transform =
    `translate(0,-50%) rotate(${secDeg}deg)`;
  document.querySelector('.min-hand').style.transform =
    `translate(0,-50%) rotate(${minDeg}deg)`;
  document.querySelector('.hour-hand').style.transform =
    `translate(0,-50%) rotate(${hrDeg}deg)`;
}

document.addEventListener('DOMContentLoaded', () => {
  updateDigitalClock(); setInterval(updateDigitalClock, 1000);
  updateAnalogClock();  setInterval(updateAnalogClock, 1000);
  disableIfLoggedThisBlock();
  scheduleChime();
  setupLogButton();
});

