 document.addEventListener('DOMContentLoaded', () => {

 // ---------- Clock ----------
    (function startClock(){
      const tEl = document.getElementById('clock-time');
      const dEl = document.getElementById('clock-date');

      function pad(n){ return String(n).padStart(2,'0'); }

      function update(){
        const now = new Date();
        const hours = now.getHours();
        const minutes = now.getMinutes();
        const seconds = now.getSeconds();

        // 12-hour format with AM/PM
        const ampm = hours >= 12 ? 'PM' : 'AM';
        const h12 = ((hours + 11) % 12) + 1;

        tEl.textContent = `${pad(h12)}:${pad(minutes)}:${pad(seconds)} ${ampm}`;

        // e.g., Tuesday, Nov 18, 2025
        const dateOptions = { weekday: 'long', year: 'numeric', month: 'short', day: 'numeric' };
        dEl.textContent = now.toLocaleDateString(undefined, dateOptions);
      }

      update();
      setInterval(update, 1000);
    })();

    // ---------- Todo list ----------
    (function todoApp(){
      const input = document.getElementById('todo-input');
      const addBtn = document.getElementById('add-btn');
      const listEl = document.getElementById('todo-list');
      const tasksCountEl = document.getElementById('tasks-count');
      const completedCountEl = document.getElementById('completed-count');

      const STORAGE_KEY = 'simple_dashboard_todos_v1';

      // Load tasks from localStorage
      let tasks = [];
      try {
        const raw = localStorage.getItem(STORAGE_KEY);
        if(raw) tasks = JSON.parse(raw);
      } catch(e){
        console.warn('Could not parse saved tasks', e);
        tasks = [];
      }

      function save(){
        try {
          localStorage.setItem(STORAGE_KEY, JSON.stringify(tasks));
        } catch(e){
          console.warn('Could not save tasks', e);
        }
      }

      function render(){
        listEl.innerHTML = '';
        let completed = 0;

        tasks.forEach((task, idx) => {
          const li = document.createElement('li');
          li.className = 'todo-item';
          li.dataset.index = idx;

          const checkbox = document.createElement('input');
          checkbox.type = 'checkbox';
          checkbox.checked = !!task.done;
          checkbox.setAttribute('aria-label', 'Mark task complete');

          const span = document.createElement('div');
          span.className = 'todo-text' + (task.done ? ' done' : '');
          span.textContent = task.text;

          const actions = document.createElement('div');
          actions.className = 'todo-actions';

          const delBtn = document.createElement('button');
          delBtn.className = 'btn-small btn-delete';
          delBtn.type = 'button';
          delBtn.textContent = 'Delete';
          delBtn.setAttribute('aria-label', 'Delete task');

          // events
          checkbox.addEventListener('change', () => {
            tasks[idx].done = checkbox.checked;
            save();
            render();
          });

          delBtn.addEventListener('click', () => {
            tasks.splice(idx,1);
            save();
            render();
          });

          // double-click to edit (simple inline)
          span.addEventListener('dblclick', () => {
            const newText = prompt('Edit task', task.text);
            if(newText !== null){
              tasks[idx].text = newText.trim() || task.text;
              save();
              render();
            }
          });

          actions.appendChild(delBtn);
          li.appendChild(checkbox);
          li.appendChild(span);
          li.appendChild(actions);

          listEl.appendChild(li);

          if(task.done) completed++;
        });

        tasksCountEl.textContent = tasks.length;
        completedCountEl.textContent = completed;
      }

      function addTask(text){
        const trimmed = String(text || '').trim();
        if(!trimmed) return;
        tasks.unshift({ text: trimmed, done: false, createdAt: Date.now() });
        save();
        render();
      }

      // Wire up UI
      addBtn.addEventListener('click', () => {
        addTask(input.value);
        input.value = '';
        input.focus();
      });

      input.addEventListener('keydown', (e) => {
        if(e.key === 'Enter'){
          addTask(input.value);
          input.value = '';
        }
      });

      // initial render
      render();

      // Optional: clear completed older than 30 days (keeps storage tidy)
      // This is non-intrusive; comment out if you prefer to keep everything.
      (function cleanupOldCompleted(){
        const THIRTY_DAYS = 1000 * 60 * 60 * 24 * 30;
        const now = Date.now();
        const before = tasks.length;
        tasks = tasks.filter(t => !(t.done && (now - (t.createdAt || 0) > THIRTY_DAYS)));
        if(tasks.length !== before) save();
      })();
    })();
    });