<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My Tasks — Dealspace</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
  <script src="https://cdn.tailwindcss.com"></script>
  <style>
    * { font-family: 'Inter', sans-serif; }
    body { background: #0a1628; margin: 0; }
    .sidebar-link.active { background: rgba(201,168,76,0.1); color: #c9a84c; border-left: 3px solid #c9a84c; }
    .sidebar-link:hover:not(.active) { background: rgba(255,255,255,0.04); }
    .task-card:hover { border-color: rgba(201,168,76,0.3); transform: translateY(-1px); }
    .priority-high { background: #ef4444; }
    .priority-normal { background: #c9a84c; }
    .priority-low { background: #22c55e; }
  </style>
</head>
<body>
  <!-- Top Nav -->
  <header class="bg-[#0d1f3c] border-b border-white/[0.08] px-6 py-3 flex items-center justify-between sticky top-0 z-50">
    <div class="flex items-center gap-6">
      <a href="/app/tasks" class="text-xl font-bold text-white tracking-tight">
        <span class="text-[#c9a84c]">Deal</span>space
      </a>
      <select id="projectSwitcher" class="bg-[#0a1628] border border-white/[0.08] rounded-lg px-3 py-1.5 text-sm text-white focus:outline-none focus:border-[#c9a84c]">
        <option value="">All Projects</option>
      </select>
    </div>
    <div class="flex items-center gap-4">
      <span id="userName" class="text-sm text-[#b0bec5]"></span>
      <button onclick="logout()" class="text-sm text-[#b0bec5] hover:text-white transition">Logout</button>
    </div>
  </header>

  <div class="flex">
    <!-- Sidebar -->
    <nav class="w-56 bg-[#0d1f3c] border-r border-white/[0.08] min-h-[calc(100vh-49px)] sticky top-[49px] shrink-0">
      <div class="p-3 space-y-0.5">
        <a href="/app/tasks" class="sidebar-link active flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium text-white transition">
          <svg class="w-4 h-4 text-[#b0bec5]" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4"/></svg>
          My Tasks
        </a>
        <a href="/app/projects" class="sidebar-link flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium text-[#b0bec5] transition">
          <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"/></svg>
          Projects
        </a>
        <div id="adminLinks" class="hidden">
          <div class="border-t border-white/[0.08] my-3"></div>
          <a href="/admin" class="sidebar-link flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium text-[#b0bec5] transition">
            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/></svg>
            Admin
          </a>
        </div>
      </div>
    </nav>

    <!-- Main Content -->
    <main class="flex-1 p-8 max-w-5xl">
      <!-- Greeting -->
      <div class="mb-8">
        <h1 id="greeting" class="text-2xl font-bold text-white mb-1"></h1>
        <p class="text-[#b0bec5] text-sm">Here are your pending tasks.</p>
      </div>

      <!-- Task List -->
      <div id="taskList" class="space-y-3">
        <div class="text-[#b0bec5] text-sm">Loading tasks...</div>
      </div>

      <!-- Empty State -->
      <div id="emptyState" class="hidden text-center py-20">
        <div class="text-5xl mb-4">&#127881;</div>
        <h2 class="text-xl font-semibold text-white mb-2">You're all caught up</h2>
        <p class="text-[#b0bec5]">No tasks need your attention right now.</p>
      </div>
    </main>
  </div>

  <script>
    // Auth check
    const token = localStorage.getItem('ds_token');
    if (!token) { window.location.href = '/app/login'; }

    const user = JSON.parse(localStorage.getItem('ds_user') || '{}');

    function fetchAPI(path, opts = {}) {
      opts.headers = { ...opts.headers, 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' };
      return fetch(path, opts).then(r => {
        if (r.status === 401) { localStorage.removeItem('ds_token'); window.location.href = '/app/login'; }
        return r;
      });
    }

    function logout() {
      fetchAPI('/api/auth/logout', { method: 'POST' }).finally(() => {
        localStorage.removeItem('ds_token');
        localStorage.removeItem('ds_user');
        window.location.href = '/app/login';
      });
    }

    // Greeting
    const hour = new Date().getHours();
    const greetWord = hour < 12 ? 'Good morning' : hour < 18 ? 'Good afternoon' : 'Good evening';
    document.getElementById('greeting').textContent = greetWord + ', ' + (user.name || 'there');
    document.getElementById('userName').textContent = user.name || user.email || '';
    if (user.is_super_admin) document.getElementById('adminLinks').classList.remove('hidden');

    // Load tasks
    async function loadTasks() {
      try {
        const res = await fetchAPI('/api/tasks');
        const tasks = await res.json();
        const list = document.getElementById('taskList');
        const empty = document.getElementById('emptyState');

        if (!tasks || tasks.length === 0) {
          list.classList.add('hidden');
          empty.classList.remove('hidden');
          return;
        }

        list.innerHTML = tasks.map(t => {
          const data = parseData(t.data_text);
          const priority = data.priority || 'normal';
          const title = data.title || t.summary || 'Untitled';
          const ref = data.ref || '';
          const due = data.due_date || '';
          const status = data.status || 'open';
          const projectName = t.project_id ? t.project_id.substring(0, 8) : '';

          return `
            <a href="/app/requests/${t.entry_id}" class="task-card block bg-[#0d1f3c] border border-white/[0.08] rounded-xl p-5 transition cursor-pointer">
              <div class="flex items-center gap-3 mb-2">
                <span class="w-2.5 h-2.5 rounded-full priority-${priority} shrink-0"></span>
                ${ref ? `<span class="text-xs font-mono text-[#b0bec5]">${ref}</span>` : ''}
                <span class="text-white font-medium flex-1">${escapeHtml(title)}</span>
                ${due ? `<span class="text-xs text-[#b0bec5]">Due: ${due}</span>` : ''}
              </div>
              <div class="flex items-center gap-3 text-xs text-[#8899a6]">
                <span class="capitalize px-2 py-0.5 rounded-full bg-white/[0.05] text-[#b0bec5]">${status}</span>
                <span>${t.type || 'request'}</span>
              </div>
            </a>
          `;
        }).join('');
      } catch (err) {
        document.getElementById('taskList').innerHTML = '<div class="text-red-400 text-sm">Failed to load tasks.</div>';
      }
    }

    function parseData(text) {
      if (!text) return {};
      try { return JSON.parse(text); } catch { return {}; }
    }

    function escapeHtml(s) {
      const d = document.createElement('div');
      d.textContent = s;
      return d.innerHTML;
    }

    loadTasks();
  </script>
</body>
</html>
