<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Ecolist — Team Checklist</title>
  <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;500;600&family=Playfair+Display:ital,wght@0,400;1,400&display=swap" rel="stylesheet">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <style>
    *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
    :root {
      --bg:        #f9f6f0;
      --bg-card:   #ffffff;
      --bg-2:      #f2ede5;
      --border:    rgba(0,0,0,0.08);
      --text:      #1a1612;
      --text-dim:  rgba(26,22,18,0.65);
      --text-muted:rgba(26,22,18,0.42);
      --emerald:   #16a34a;
      --emerald-d: #15803d;
      --emerald-bg:rgba(22,163,74,0.09);
      --amber:     #d97706;
      --amber-bg:  rgba(217,119,6,0.09);
      --red:       #dc2626;
      --red-bg:    rgba(220,38,38,0.09);
      --ff-body:   'Outfit', system-ui, sans-serif;
      --ff-disp:   'Playfair Display', Georgia, serif;
    }
    body { background: var(--bg); font-family: var(--ff-body); min-height: 100vh; color: var(--text); }

    /* ── Header ── */
    .header { background: var(--bg-card); border-bottom: 1px solid var(--border); padding: 0 24px; display: flex; align-items: center; justify-content: space-between; height: 56px; position: sticky; top: 0; z-index: 10; }
    .header-logo { display: flex; align-items: center; gap: 9px; text-decoration: none; color: var(--text); }
    .header-logo span { font-family: var(--ff-disp); font-size: 19px; letter-spacing: -0.02em; }
    .header-logo span em { color: var(--emerald); font-style: normal; }
    .header-right { display: flex; align-items: center; gap: 16px; }
    .stats { display: flex; gap: 16px; }
    .stat { font-size: 13px; color: var(--text-dim); }
    .stat strong { color: var(--text); font-weight: 600; }
    .logout-btn { font-size: 13px; color: var(--text-muted); text-decoration: none; padding: 5px 10px; border: 1px solid var(--border); border-radius: 6px; transition: all .15s; }
    .logout-btn:hover { color: var(--red); border-color: var(--red); }

    /* ── Container ── */
    .container { max-width: 860px; margin: 0 auto; padding: 28px 20px; }

    /* ── Add task form ── */
    .add-form { background: var(--bg-card); border: 1px solid var(--border); border-radius: 12px; padding: 20px; margin-bottom: 24px; display: flex; gap: 10px; flex-wrap: wrap; }
    .add-form input[type="text"] { flex: 1; min-width: 200px; padding: 10px 14px; border: 1px solid var(--border); border-radius: 8px; font-family: var(--ff-body); font-size: 14.5px; color: var(--text); background: var(--bg); outline: none; transition: border-color .15s; }
    .add-form input:focus { border-color: var(--emerald); }
    .add-form select { padding: 10px 12px; border: 1px solid var(--border); border-radius: 8px; font-family: var(--ff-body); font-size: 14px; color: var(--text); background: var(--bg); outline: none; cursor: pointer; }
    .add-form select:focus { border-color: var(--emerald); }
    .btn-add { padding: 10px 20px; background: var(--emerald); color: #fff; border: none; border-radius: 8px; font-family: var(--ff-body); font-size: 14.5px; font-weight: 500; cursor: pointer; transition: background .15s; white-space: nowrap; }
    .btn-add:hover { background: var(--emerald-d); }

    /* ── Filters ── */
    .filters { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 20px; align-items: center; }
    .filters-label { font-size: 12px; font-weight: 500; color: var(--text-muted); text-transform: uppercase; letter-spacing: .06em; margin-right: 4px; }
    .filter-btn { padding: 5px 12px; border: 1px solid var(--border); border-radius: 20px; font-family: var(--ff-body); font-size: 13px; color: var(--text-dim); background: var(--bg-card); cursor: pointer; transition: all .15s; }
    .filter-btn:hover, .filter-btn.active { background: var(--text); color: #fff; border-color: var(--text); }
    .filter-btn.active-cat { background: var(--emerald-bg); color: var(--emerald); border-color: rgba(22,163,74,.25); font-weight: 500; }

    /* ── Task list ── */
    .tasks { display: flex; flex-direction: column; gap: 10px; }

    /* ── Task card ── */
    .task-card { background: var(--bg-card); border: 1px solid var(--border); border-radius: 12px; overflow: hidden; transition: box-shadow .15s; }
    .task-card:hover { box-shadow: 0 2px 12px rgba(0,0,0,0.07); }
    .task-card.is-done { opacity: .55; }
    .task-card.is-done .task-title { text-decoration: line-through; color: var(--text-muted); }

    /* urgency left border */
    .task-card[data-urgent="high"]   { border-left: 3px solid var(--red); }
    .task-card[data-urgent="medium"] { border-left: 3px solid var(--amber); }
    .task-card[data-urgent="low"]    { border-left: 3px solid var(--emerald); }

    .task-main { display: flex; align-items: center; gap: 12px; padding: 14px 16px; }
    .task-done-btn { flex-shrink: 0; width: 26px; height: 26px; border-radius: 50%; border: 2px solid var(--border); background: transparent; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: all .15s; }
    .task-done-btn:hover { border-color: var(--emerald); }
    .task-done-btn.done { background: var(--emerald); border-color: var(--emerald); }
    .task-done-btn .material-icons { font-size: 15px; color: #fff; display: none; }
    .task-done-btn.done .material-icons { display: block; }

    .task-body { flex: 1; min-width: 0; }
    .task-title { font-size: 14.5px; font-weight: 400; line-height: 1.45; color: var(--text); margin-bottom: 5px; }
    .task-meta { display: flex; gap: 6px; flex-wrap: wrap; align-items: center; }

    /* urgency badge */
    .badge-urgent { display: inline-flex; align-items: center; gap: 4px; padding: 3px 9px; border-radius: 20px; font-size: 11.5px; font-weight: 500; cursor: pointer; border: none; font-family: var(--ff-body); transition: all .15s; }
    .badge-urgent[data-level="high"]   { background: var(--red-bg);   color: var(--red); }
    .badge-urgent[data-level="medium"] { background: var(--amber-bg); color: var(--amber); }
    .badge-urgent[data-level="low"]    { background: var(--emerald-bg); color: var(--emerald); }
    .badge-urgent:hover { opacity: .8; }

    /* category badge */
    .badge-cat { display: inline-flex; align-items: center; padding: 3px 9px; border-radius: 20px; font-size: 11.5px; font-weight: 500; background: var(--bg-2); color: var(--text-dim); }

    .task-actions { display: flex; align-items: center; gap: 6px; flex-shrink: 0; }
    .icon-btn { width: 32px; height: 32px; border: none; background: transparent; cursor: pointer; border-radius: 6px; display: flex; align-items: center; justify-content: center; color: var(--text-muted); transition: all .15s; }
    .icon-btn:hover { background: var(--bg-2); color: var(--text); }
    .icon-btn.delete-btn:hover { background: #fef2f2; color: var(--red); }
    .icon-btn.notes-btn.open { color: var(--emerald); }
    .icon-btn .material-icons { font-size: 18px; }

    /* notes panel */
    .task-notes { overflow: hidden; max-height: 0; transition: max-height .25s ease; }
    .task-notes.open { max-height: 200px; }
    .notes-inner { padding: 0 16px 14px 54px; }
    .notes-textarea { width: 100%; min-height: 72px; padding: 10px 12px; border: 1px solid var(--border); border-radius: 8px; font-family: var(--ff-body); font-size: 13.5px; color: var(--text); background: var(--bg); resize: vertical; outline: none; transition: border-color .15s; line-height: 1.5; }
    .notes-textarea:focus { border-color: var(--emerald); }
    .notes-save-hint { font-size: 11.5px; color: var(--text-muted); margin-top: 5px; }

    /* ── Empty state ── */
    .empty { text-align: center; padding: 60px 20px; color: var(--text-muted); }
    .empty .material-icons { font-size: 40px; margin-bottom: 12px; display: block; }
    .empty p { font-size: 15px; }

    /* ── Hidden tasks ── */
    .task-card.hidden { display: none; }

    @media (max-width: 600px) {
      .stats { display: none; }
      .add-form { gap: 8px; }
      .add-form input[type="text"] { min-width: 0; }
      .notes-inner { padding-left: 16px; }
    }
  </style>
</head>
<body>

<header class="header">
  <a class="header-logo" href="/">
    <svg width="24" height="24" viewBox="0 0 26 26" fill="none">
      <circle cx="13" cy="13" r="12" stroke="#1a1612" stroke-width="1"/>
      <path d="M7 13C7 9.686 9.686 7 13 7s6 2.686 6 6-2.686 6-6 6" stroke="#16a34a" stroke-width="1.5" stroke-linecap="round"/>
      <circle cx="13" cy="13" r="2" fill="#16a34a"/>
    </svg>
    <span>eco<em>list</em></span>
  </a>
  <div class="header-right">
    <div class="stats" id="statsBar">
      <span class="stat"><strong id="statTotal">0</strong> tasks</span>
      <span class="stat"><strong id="statDone">0</strong> done</span>
    </div>
    <a class="logout-btn" href="/ecolist/logout">Logout</a>
  </div>
</header>

<div class="container">

  <!-- Add task -->
  <form class="add-form" id="addForm">
    <input type="text" id="newTitle" placeholder="New task title…" required>
    <select id="newCat">
      <option value="Admin">Admin</option>
      <option value="IT">IT</option>
      <option value="Back Office">Back Office</option>
      <option value="Finances">Finances</option>
      <option value="General">General</option>
    </select>
    <button type="submit" class="btn-add">+ Add Task</button>
  </form>

  <!-- Filters -->
  <div class="filters">
    <span class="filters-label">Filter:</span>
    <button class="filter-btn active" data-filter="all">All</button>
    <button class="filter-btn" data-filter="pending">Pending</button>
    <button class="filter-btn" data-filter="done">Done</button>
    <button class="filter-btn" data-filter="urgent-high">🔴 Very Urgent</button>
    <button class="filter-btn" data-filter="urgent-medium">🟡 Urgent</button>
    <span style="width:1px; height:16px; background:var(--border); margin:0 4px;"></span>
    <button class="filter-btn" data-filter="cat-Admin">Admin</button>
    <button class="filter-btn" data-filter="cat-IT">IT</button>
    <button class="filter-btn" data-filter="cat-Back Office">Back Office</button>
    <button class="filter-btn" data-filter="cat-Finances">Finances</button>
  </div>

  <!-- Task list -->
  <div class="tasks" id="taskList">
    <% tasks.forEach(function(t) { %>
    <div class="task-card <%= t.done ? 'is-done' : '' %>" data-id="<%= t.id %>" data-urgent="<%= t.urgent %>" data-cat="<%= t.category %>" data-done="<%= t.done ? '1' : '0' %>">
      <div class="task-main">
        <button class="task-done-btn <%= t.done ? 'done' : '' %>" onclick="toggleDone(this)" title="Toggle done">
          <span class="material-icons">check</span>
        </button>
        <div class="task-body">
          <div class="task-title"><%= t.title %></div>
          <div class="task-meta">
            <button class="badge-urgent" data-level="<%= t.urgent %>" onclick="cycleUrgent(this)">
              <% if (t.urgent === 'high') { %>🔴 Very Urgent<% } else if (t.urgent === 'medium') { %>🟡 Urgent<% } else { %>🟢 Not Urgent<% } %>
            </button>
            <span class="badge-cat"><%= t.category %></span>
          </div>
        </div>
        <div class="task-actions">
          <button class="icon-btn notes-btn" onclick="toggleNotes(this)" title="Notes">
            <span class="material-icons">notes</span>
          </button>
          <button class="icon-btn delete-btn" onclick="deleteTask(this)" title="Delete">
            <span class="material-icons">delete_outline</span>
          </button>
        </div>
      </div>
      <div class="task-notes <%= t.notes ? 'open' : '' %>">
        <div class="notes-inner">
          <textarea class="notes-textarea" placeholder="Add notes or explanation…" onblur="saveNotes(this)"><%= t.notes || '' %></textarea>
          <div class="notes-save-hint">Saves automatically on blur</div>
        </div>
      </div>
    </div>
    <% }); %>
  </div>

  <div class="empty" id="emptyState" style="display:none">
    <span class="material-icons">checklist</span>
    <p>No tasks match this filter.</p>
  </div>
</div>

<script>
  const BASE = '/ecolist';
  let activeFilter = 'all';

  // ── Patch request helper ─────────────────────────────────────────────────
  async function patch(id, data) {
    await fetch(BASE + '/api/tasks/' + id, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(data)
    });
  }

  // ── Toggle done ──────────────────────────────────────────────────────────
  function toggleDone(btn) {
    const card = btn.closest('.task-card');
    const isDone = !card.dataset.done || card.dataset.done === '0';
    card.dataset.done = isDone ? '1' : '0';
    card.classList.toggle('is-done', isDone);
    btn.classList.toggle('done', isDone);
    patch(card.dataset.id, { done: isDone });
    applyFilter(activeFilter);
    updateStats();
  }

  // ── Cycle urgency ────────────────────────────────────────────────────────
  const URGENCY = [
    { level: 'high',   label: '🔴 Very Urgent' },
    { level: 'medium', label: '🟡 Urgent' },
    { level: 'low',    label: '🟢 Not Urgent' }
  ];

  function cycleUrgent(btn) {
    const card = btn.closest('.task-card');
    const cur = URGENCY.findIndex(u => u.level === btn.dataset.level);
    const next = URGENCY[(cur + 1) % URGENCY.length];
    btn.dataset.level = next.level;
    btn.textContent = next.label;
    card.dataset.urgent = next.level;
    patch(card.dataset.id, { urgent: next.level });
  }

  // ── Toggle notes panel ───────────────────────────────────────────────────
  function toggleNotes(btn) {
    const card = btn.closest('.task-card');
    const panel = card.querySelector('.task-notes');
    const isOpen = panel.classList.toggle('open');
    btn.classList.toggle('open', isOpen);
    if (isOpen) card.querySelector('.notes-textarea').focus();
  }

  // ── Save notes on blur ───────────────────────────────────────────────────
  function saveNotes(textarea) {
    const card = textarea.closest('.task-card');
    patch(card.dataset.id, { notes: textarea.value });
  }

  // ── Delete task ──────────────────────────────────────────────────────────
  async function deleteTask(btn) {
    if (!confirm('Delete this task?')) return;
    const card = btn.closest('.task-card');
    const res = await fetch(BASE + '/api/tasks/' + card.dataset.id, { method: 'DELETE' });
    if (res.ok) { card.remove(); updateStats(); applyFilter(activeFilter); }
  }

  // ── Add task ─────────────────────────────────────────────────────────────
  document.getElementById('addForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const title = document.getElementById('newTitle').value.trim();
    const category = document.getElementById('newCat').value;
    if (!title) return;
    const res = await fetch(BASE + '/api/tasks', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ title, category })
    });
    if (!res.ok) return;
    const task = await res.json();
    document.getElementById('newTitle').value = '';
    document.getElementById('taskList').insertAdjacentHTML('beforeend', buildCard(task));
    updateStats();
    applyFilter(activeFilter);
  });

  function buildCard(t) {
    return `
      <div class="task-card" data-id="${t.id}" data-urgent="low" data-cat="${esc(t.category)}" data-done="0">
        <div class="task-main">
          <button class="task-done-btn" onclick="toggleDone(this)" title="Toggle done">
            <span class="material-icons">check</span>
          </button>
          <div class="task-body">
            <div class="task-title">${esc(t.title)}</div>
            <div class="task-meta">
              <button class="badge-urgent" data-level="low" onclick="cycleUrgent(this)">🟢 Not Urgent</button>
              <span class="badge-cat">${esc(t.category)}</span>
            </div>
          </div>
          <div class="task-actions">
            <button class="icon-btn notes-btn" onclick="toggleNotes(this)" title="Notes">
              <span class="material-icons">notes</span>
            </button>
            <button class="icon-btn delete-btn" onclick="deleteTask(this)" title="Delete">
              <span class="material-icons">delete_outline</span>
            </button>
          </div>
        </div>
        <div class="task-notes">
          <div class="notes-inner">
            <textarea class="notes-textarea" placeholder="Add notes or explanation…" onblur="saveNotes(this)"></textarea>
            <div class="notes-save-hint">Saves automatically on blur</div>
          </div>
        </div>
      </div>`;
  }

  function esc(s) {
    return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
  }

  // ── Filters ──────────────────────────────────────────────────────────────
  document.querySelectorAll('.filter-btn').forEach(btn => {
    btn.addEventListener('click', () => {
      document.querySelectorAll('.filter-btn').forEach(b => b.classList.remove('active'));
      btn.classList.add('active');
      activeFilter = btn.dataset.filter;
      applyFilter(activeFilter);
    });
  });

  function applyFilter(f) {
    let visible = 0;
    document.querySelectorAll('.task-card').forEach(card => {
      let show = true;
      if (f === 'pending') show = card.dataset.done === '0';
      else if (f === 'done') show = card.dataset.done === '1';
      else if (f === 'urgent-high') show = card.dataset.urgent === 'high' && card.dataset.done === '0';
      else if (f === 'urgent-medium') show = card.dataset.urgent === 'medium' && card.dataset.done === '0';
      else if (f.startsWith('cat-')) show = card.dataset.cat === f.slice(4);
      card.classList.toggle('hidden', !show);
      if (show) visible++;
    });
    document.getElementById('emptyState').style.display = visible === 0 ? 'block' : 'none';
  }

  // ── Stats ─────────────────────────────────────────────────────────────────
  function updateStats() {
    const cards = document.querySelectorAll('.task-card');
    const done  = document.querySelectorAll('.task-card.is-done');
    document.getElementById('statTotal').textContent = cards.length;
    document.getElementById('statDone').textContent  = done.length;
  }

  updateStats();
  applyFilter('all');
</script>
</body>
</html>
