<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Project — Dealspace</title>
  <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; }
    .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); }
    .tab.active { color: #c9a84c; border-bottom: 2px solid #c9a84c; }
    .tab { border-bottom: 2px solid transparent; }

    /* Tree table styles */
    #reqTree { border-collapse: collapse; width: 100%; font-size: 13px; }
    #reqTree th { text-align: left; padding: 6px 10px; font-weight: 600; font-size: 11px; text-transform: uppercase; letter-spacing: 0.05em; color: var(--ds-tx3, #475569); border-bottom: 1px solid var(--ds-bd, rgba(255,255,255,.08)); user-select: none; white-space: nowrap; }
    #reqTree td { padding: 5px 10px; border-bottom: 1px solid var(--ds-bd, rgba(255,255,255,.08)); vertical-align: middle; white-space: nowrap; }
    #reqTree tbody tr { transition: background .1s; }
    #reqTree tbody tr:hover { background: var(--ds-hv, rgba(255,255,255,.04)); }
    #reqTree tbody tr.row-list { background: var(--ds-sf, #0d1f3c); }
    #reqTree tbody tr.row-list:hover { background: color-mix(in srgb, var(--ds-sf, #0d1f3c) 85%, var(--ds-tx, white)); }
    #reqTree tbody tr.row-section { background: rgba(255,255,255,.02); }
    #reqTree .drag-handle { cursor: grab; opacity: 0.3; transition: opacity .15s; }
    #reqTree tr:hover .drag-handle { opacity: 0.8; }
    #reqTree .row-num { font-variant-numeric: tabular-nums; font-size: 12px; color: var(--ds-tx3, #475569); }
    #reqTree .collapse-btn { cursor: pointer; user-select: none; display: inline-block; width: 16px; text-align: center; font-size: 10px; color: var(--ds-tx3, #475569); transition: transform .15s; }
    #reqTree .collapse-btn.collapsed { transform: rotate(-90deg); }
    .drop-above { box-shadow: 0 -2px 0 var(--ds-ac, #c9a84c) inset; }
    .drop-below { box-shadow: 0 2px 0 var(--ds-ac, #c9a84c) inset; }
    .drop-into { box-shadow: inset 0 0 0 1px var(--ds-ac, #c9a84c); }
    .badge { display: inline-block; padding: 1px 8px; border-radius: 9999px; font-size: 11px; font-weight: 500; line-height: 18px; }
    .actions-menu { position: absolute; right: 0; top: 100%; background: var(--ds-sf, #0d1f3c); border: 1px solid var(--ds-bd); border-radius: 8px; padding: 4px 0; min-width: 160px; z-index: 100; box-shadow: 0 8px 24px rgba(0,0,0,.4); }
    .actions-menu button { display: block; width: 100%; text-align: left; padding: 6px 14px; font-size: 13px; color: var(--ds-tx2, #94a3b8); background: none; border: none; cursor: pointer; }
    .actions-menu button:hover { background: var(--ds-hv); color: var(--ds-tx, #fff); }
  </style>
  <style id="ds-themes">
    :root,html[data-theme="midnight"]{--ds-bg:#0a1628;--ds-sf:#0d1f3c;--ds-tx:#fff;--ds-tx2:#94a3b8;--ds-tx3:#475569;--ds-ac:#c9a84c;--ds-ac2:#b8973f;--ds-act:#0a1628;--ds-bd:rgba(255,255,255,.08);--ds-hv:rgba(255,255,255,.04);--ds-inp:#0a1628;--ds-hf:'Inter',sans-serif}
    html[data-theme="light"]{--ds-bg:#f0f2f5;--ds-sf:#fff;--ds-tx:#1a202c;--ds-tx2:#64748b;--ds-tx3:#94a3b8;--ds-ac:#2563eb;--ds-ac2:#1d4ed8;--ds-act:#fff;--ds-bd:rgba(0,0,0,.08);--ds-hv:rgba(0,0,0,.05);--ds-inp:#f8fafc;--ds-hf:'Inter',sans-serif}
    html[data-theme="slate"]{--ds-bg:#1e293b;--ds-sf:#334155;--ds-tx:#f1f5f9;--ds-tx2:#94a3b8;--ds-tx3:#64748b;--ds-ac:#14b8a6;--ds-ac2:#0d9488;--ds-act:#0f172a;--ds-bd:rgba(148,163,184,.12);--ds-hv:rgba(255,255,255,.05);--ds-inp:#1e293b;--ds-hf:'Inter',sans-serif}
    html[data-theme="compact"]{font-size:13.5px;--ds-bg:#0a1628;--ds-sf:#0d1f3c;--ds-tx:#fff;--ds-tx2:#94a3b8;--ds-tx3:#475569;--ds-ac:#c9a84c;--ds-ac2:#b8973f;--ds-act:#0a1628;--ds-bd:rgba(255,255,255,.08);--ds-hv:rgba(255,255,255,.04);--ds-inp:#0a1628;--ds-hf:'Inter',sans-serif}
    html[data-theme="executive"]{font-size:17px;--ds-bg:#1a1410;--ds-sf:#2a2218;--ds-tx:#f5f0e8;--ds-tx2:#c4b8a4;--ds-tx3:#8a7e6e;--ds-ac:#d4a843;--ds-ac2:#c49835;--ds-act:#1a1410;--ds-bd:rgba(196,184,164,.12);--ds-hv:rgba(212,168,67,.06);--ds-inp:#1a1410;--ds-hf:'Georgia','Times New Roman',serif}
    body{background:var(--ds-bg)!important}
    h1,h2,h3{font-family:var(--ds-hf)!important}
    html[data-theme="executive"] *{font-family:'Georgia','Times New Roman',serif!important}
    header{background:var(--ds-sf)!important;border-color:var(--ds-bd)!important}
    nav{background:var(--ds-sf)!important;border-color:var(--ds-bd)!important}
    .text-white{color:var(--ds-tx)!important}
    [class*="text-white/"]{color:var(--ds-tx3)!important}
    .sidebar-link.active{background:color-mix(in srgb,var(--ds-ac) 10%,transparent)!important;color:var(--ds-ac)!important;border-left-color:var(--ds-ac)!important}
    .sidebar-link:hover:not(.active){background:var(--ds-hv)!important}
    [class*="bg-[#0d1f3c]"]{background-color:var(--ds-sf)!important}
    [class*="bg-[#0a1628]"]{background-color:var(--ds-bg)!important}
    [class*="text-[#c9a84c]"]{color:var(--ds-ac)!important}
    [class*="text-[#94a3b8]"]{color:var(--ds-tx2)!important}
    [class*="text-[#475569]"]{color:var(--ds-tx3)!important}
    [class*="text-[#0a1628]"]{color:var(--ds-act)!important}
    [class*="bg-[#c9a84c]"]{background-color:var(--ds-ac)!important}
    [class*="hover:bg-[#b8973f]"]:hover{background-color:var(--ds-ac2)!important}
    [class*="border-white"]{border-color:var(--ds-bd)!important}
    [class*="bg-white/"]{background-color:var(--ds-hv)!important}
    [class*="hover:bg-white/"]:hover{background-color:var(--ds-hv)!important}
    input,textarea,select{background-color:var(--ds-inp)!important;color:var(--ds-tx)!important;border-color:var(--ds-bd)!important}
    input:focus,textarea:focus,select:focus{border-color:var(--ds-ac)!important}
    [class*="bg-black/"]{background-color:rgba(0,0,0,.6)!important}
    .tab.active{color:var(--ds-ac)!important;border-bottom-color:var(--ds-ac)!important}
    #ds-theme-bar{position:fixed;bottom:20px;right:20px;z-index:9999;display:flex;gap:3px;padding:4px;background:var(--ds-sf);border:1px solid var(--ds-bd);border-radius:12px;box-shadow:0 4px 20px rgba(0,0,0,.3)}
    #ds-theme-bar button{padding:5px 10px;border-radius:8px;border:none;cursor:pointer;background:transparent;color:var(--ds-tx2);white-space:nowrap;transition:all .15s;font-size:12px}
    #ds-theme-bar button:hover{background:var(--ds-hv)}
    #ds-theme-bar button.active{background:var(--ds-ac);color:var(--ds-act);font-weight:600}
    #ds-theme-bar,#ds-theme-bar *{font-family:'Inter',sans-serif!important}
  </style>
  <script>document.documentElement.setAttribute('data-theme',localStorage.getItem('ds_theme')||'midnight')</script>
</head>
<body>
  <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-3">
      <a href="/app/projects" class="text-xl font-bold text-white tracking-tight"><span class="text-[#c9a84c]">Deal</span>space</a>
      <span class="text-white/20">/</span>
      <a href="/app/projects" class="text-sm text-[#94a3b8] hover:text-white transition">Projects</a>
      <span class="text-white/20">/</span>
      <span id="projectName" class="text-sm text-white font-medium">Loading...</span>
    </div>
    <div class="flex items-center gap-4">
      <span id="userName" class="text-sm text-[#94a3b8]"></span>
      <button onclick="logout()" class="text-sm text-[#94a3b8] hover:text-white transition">Logout</button>
    </div>
  </header>
  <div class="flex">
    <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 flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium text-[#94a3b8] 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="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 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" 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>
        <a href="/app/orgs" class="sidebar-link flex items-center gap-3 px-3 py-2.5 rounded-lg text-sm font-medium text-[#94a3b8] 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="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4"/></svg>
          Organizations</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-[#94a3b8] 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 class="flex-1 p-8" style="max-width:calc(100vw - 14rem)">
      <!-- Header -->
      <div class="flex items-start justify-between mb-6">
        <div>
          <div class="flex items-center gap-3 mb-1">
            <h1 id="projectTitle" class="text-2xl font-bold text-white">Loading...</h1>
            <span id="projectStatus" class="px-2.5 py-0.5 rounded-full text-xs font-medium"></span>
          </div>
          <p id="projectDesc" class="text-[#94a3b8] text-sm"></p>
        </div>
        <div class="flex gap-2">
          <button onclick="openImportModal()" class="px-4 py-2 bg-white/[0.05] hover:bg-white/[0.08] text-white rounded-lg text-sm transition flex items-center gap-2">
            <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="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"/></svg>
            Import
          </button>
        </div>
      </div>

      <!-- Tabs -->
      <div class="flex gap-6 border-b border-white/[0.08] mb-6">
        <button class="tab active pb-3 text-sm font-medium transition" onclick="switchTab('requests', this)">Requests</button>
        <button class="tab pb-3 text-sm font-medium text-[#94a3b8] transition" onclick="switchTab('orgs', this)">Organizations</button>
        <button class="tab pb-3 text-sm font-medium text-[#94a3b8] transition" onclick="switchTab('team', this)">Team</button>
      </div>

      <!-- Requests Tab -->
      <div id="tab-requests">
        <div id="requestEmpty" class="hidden text-center py-16">
          <h3 class="text-lg font-semibold text-white mb-1">No requests yet</h3>
          <p class="text-[#94a3b8] text-sm mb-4">Import a diligence checklist to get started.</p>
          <button onclick="openImportModal()" class="px-4 py-2 bg-[#c9a84c] hover:bg-[#b8973f] text-[#0a1628] font-semibold rounded-lg text-sm transition">Import Checklist</button>
        </div>
        <div id="treeWrap" class="overflow-x-auto">
          <table id="reqTree">
            <thead>
              <tr>
                <th style="width:28px"></th>
                <th style="width:60px">#</th>
                <th style="min-width:280px">Request Item</th>
                <th style="width:80px">Priority</th>
                <th style="width:90px">Status</th>
                <th style="width:50px">Docs</th>
                <th style="width:160px">Buyer Comment</th>
                <th style="width:160px">Seller Comment</th>
                <th style="width:90px">Created</th>
                <th style="width:40px"></th>
              </tr>
            </thead>
            <tbody id="treeBody">
              <tr><td colspan="10" class="text-[#94a3b8] text-sm py-4">Loading requests...</td></tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- Orgs Tab -->
      <div id="tab-orgs" class="hidden">
        <div class="flex justify-between items-center mb-4">
          <p class="text-[#94a3b8] text-sm">Organizations participating in this deal.</p>
          <button id="addOrgBtn" class="px-3 py-1.5 bg-white/[0.05] hover:bg-white/[0.08] text-white rounded-lg text-sm transition">+ Add Org</button>
        </div>
        <div id="orgList" class="space-y-3"><div class="text-[#94a3b8] text-sm">Loading...</div></div>
      </div>

      <!-- Team Tab -->
      <div id="tab-team" class="hidden">
        <div class="flex justify-between items-center mb-4">
          <p class="text-[#94a3b8] text-sm">People with access to this deal.</p>
          <button id="inviteBtn" class="px-3 py-1.5 bg-[#c9a84c] hover:bg-[#b8973f] text-[#0a1628] font-semibold rounded-lg text-sm transition">+ Invite</button>
        </div>
        <div id="teamList" class="space-y-2"><div class="text-[#94a3b8] text-sm">Loading...</div></div>
      </div>
    </main>
  </div>

  <!-- Import Modal -->
  <div id="importModal" style="display:none" class="fixed inset-0 bg-black/60 z-50 flex items-center justify-center p-4">
    <div class="bg-[#0d1f3c] border border-white/[0.08] rounded-xl p-8 w-full max-w-md">
      <h2 class="text-xl font-semibold text-white mb-6">Import Diligence Checklist</h2>
      <div id="importError" class="hidden mb-4 p-3 bg-red-500/10 border border-red-500/20 rounded-lg text-red-400 text-sm"></div>
      <div class="space-y-4">
        <div>
          <label class="block text-sm font-medium text-[#94a3b8] mb-1.5">Request List Name</label>
          <input type="text" id="importListName" placeholder="e.g. Blackstone DDQ, General Checklist"
            class="w-full px-4 py-2.5 bg-[#0a1628] border border-white/[0.08] rounded-lg text-white text-sm focus:outline-none focus:border-[#c9a84c] focus:ring-1 focus:ring-[#c9a84c]">
        </div>
        <div>
          <label class="block text-sm font-medium text-[#94a3b8] mb-1.5">File (CSV or XLSX)</label>
          <input type="file" id="importFile" accept=".csv,.xlsx,.xls" required
            class="w-full px-4 py-2.5 bg-[#0a1628] border border-white/[0.08] rounded-lg text-white text-sm focus:outline-none focus:border-[#c9a84c] focus:ring-1 focus:ring-[#c9a84c]">
        </div>
        <div>
          <label class="block text-sm font-medium text-[#94a3b8] mb-1.5">Import Mode</label>
          <select id="importMode" class="w-full px-4 py-2.5 bg-[#0a1628] border border-white/[0.08] rounded-lg text-white focus:outline-none focus:border-[#c9a84c]">
            <option value="add">Add new request list</option>
            <option value="replace">Replace all request lists</option>
          </select>
        </div>
      </div>
      <div class="flex gap-3 mt-6">
        <button onclick="closeImportModal()" class="flex-1 py-2.5 bg-white/[0.05] hover:bg-white/[0.08] text-white rounded-lg text-sm font-medium transition">Cancel</button>
        <button id="importBtn" onclick="submitImport()" class="flex-1 py-2.5 bg-[#c9a84c] hover:bg-[#b8973f] text-[#0a1628] font-semibold rounded-lg text-sm transition">Import</button>
      </div>
    </div>
  </div>

  <!-- Attach Answer Modal -->
  <div id="attachModal" style="display:none" class="fixed inset-0 bg-black/60 z-50 flex items-center justify-center p-4">
    <div class="bg-[#0d1f3c] border border-white/[0.08] rounded-xl p-8 w-full max-w-lg">
      <h2 class="text-xl font-semibold text-white mb-2">Attach Answer Document</h2>
      <p id="attachReqTitle" class="text-[#94a3b8] text-sm mb-4"></p>
      <div class="mb-4">
        <input type="text" id="attachSearch" placeholder="Search existing documents..."
          class="w-full px-4 py-2.5 bg-[#0a1628] border border-white/[0.08] rounded-lg text-white text-sm focus:outline-none focus:border-[#c9a84c]"
          oninput="searchAnswers(this.value)">
      </div>
      <div id="attachList" class="max-h-64 overflow-y-auto space-y-1 mb-4"></div>
      <div class="border-t border-white/[0.08] pt-4">
        <label class="block text-sm font-medium text-[#94a3b8] mb-1.5">Or upload new document</label>
        <input type="file" id="attachFile" class="w-full px-4 py-2.5 bg-[#0a1628] border border-white/[0.08] rounded-lg text-white text-sm">
      </div>
      <div class="flex gap-3 mt-4">
        <button onclick="closeAttachModal()" class="flex-1 py-2.5 bg-white/[0.05] hover:bg-white/[0.08] text-white rounded-lg text-sm font-medium transition">Cancel</button>
        <button onclick="uploadAndLink()" class="flex-1 py-2.5 bg-[#c9a84c] hover:bg-[#b8973f] text-[#0a1628] font-semibold rounded-lg text-sm transition">Upload &amp; Link</button>
      </div>
    </div>
  </div>

  <script>
    const token = localStorage.getItem('ds_token');
    if (!token) window.location.href = '/app/login';
    const user = JSON.parse(localStorage.getItem('ds_user') || '{}');
    const projectID = location.pathname.split('/').pop();
    document.getElementById('userName').textContent = user.name || user.email || '';
    if (user.is_super_admin) document.getElementById('adminLinks').classList.remove('hidden');

    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.clear(); window.location.href = '/app/login'; }); }
    function parseData(t) { try { return JSON.parse(t); } catch { return {}; } }
    function escHtml(s) { if (!s) return ''; const d = document.createElement('div'); d.textContent = s; return d.innerHTML; }
    function fmtDate(ms) { if (!ms) return ''; const d = new Date(ms); return d.toLocaleDateString('en-US', {month:'short',day:'numeric'}); }

    // Badge helpers
    function priorityBadge(p) {
      const m = { critical:'background:rgba(239,68,68,.15);color:#f87171', high:'background:rgba(251,146,60,.15);color:#fb923c', medium:'background:rgba(250,204,21,.15);color:#facc15', low:'background:rgba(148,163,184,.15);color:#94a3b8' };
      return `<span class="badge" style="${m[p]||m.medium}">${escHtml(p||'medium')}</span>`;
    }
    function statusBadge(s) {
      const m = { open:'background:rgba(96,165,250,.15);color:#60a5fa', in_process:'background:rgba(251,191,36,.15);color:#fbbf24', partial:'background:rgba(168,85,247,.15);color:#a855f7', complete:'background:rgba(74,222,128,.15);color:#4ade80' };
      const labels = { open:'Open', in_process:'In Process', partial:'Partial', complete:'Complete' };
      return `<span class="badge" style="${m[s]||m.open}">${labels[s]||escHtml(s||'open')}</span>`;
    }

    const statusColors = { active: 'bg-green-500/20 text-green-300', draft: 'bg-gray-500/20 text-gray-300', closed: 'bg-red-500/20 text-red-300' };
    const roleColors = { seller: 'bg-blue-500/20 text-blue-300', buyer: 'bg-green-500/20 text-green-300', ib: 'bg-[#c9a84c]/20 text-[#c9a84c]', advisor: 'bg-purple-500/20 text-purple-300' };

    // ---- State ----
    let treeData = [];
    let collapsed = new Set();
    let numberMap = {};
    let openMenuId = null;
    let attachRequestId = null;

    // ---- Project loading ----
    async function loadProject() {
      try {
        const res = await fetchAPI('/api/projects/' + projectID);
        if (!res.ok) { document.getElementById('projectTitle').textContent = 'Not found'; return; }
        const raw = await res.json();
        const p = raw.project || raw;
        const d = parseData(p.data_text);
        const name = d.name || p.summary_text || p.summary || 'Untitled';
        document.title = name + ' — Dealspace';
        document.getElementById('projectName').textContent = name;
        document.getElementById('projectTitle').textContent = name;
        document.getElementById('projectDesc').textContent = d.description || '';
        const status = d.status || 'active';
        const sc = statusColors[status] || 'bg-gray-500/20 text-gray-300';
        document.getElementById('projectStatus').className = 'px-2.5 py-0.5 rounded-full text-xs font-medium capitalize ' + sc;
        document.getElementById('projectStatus').textContent = status;
      } catch(e) {}
    }

    // ---- Tree loading ----
    async function loadRequestTree() {
      try {
        const res = await fetchAPI('/api/projects/' + projectID + '/requests/tree');
        treeData = await res.json();
        if (!treeData || treeData.length === 0) {
          document.getElementById('requestEmpty').classList.remove('hidden');
          document.getElementById('treeWrap').classList.add('hidden');
          return;
        }
        document.getElementById('requestEmpty').classList.add('hidden');
        document.getElementById('treeWrap').classList.remove('hidden');
        buildNumbering();
        renderTree();
      } catch(e) {
        document.getElementById('treeBody').innerHTML = '<tr><td colspan="10" class="text-red-400 text-sm py-4">Failed to load requests.</td></tr>';
      }
    }

    // Build hierarchical numbering (1, 1.1, 1.1.1, etc.)
    function buildNumbering() {
      numberMap = {};
      // Group by parent_id to count siblings
      const childrenOf = {};
      for (const item of treeData) {
        if (!childrenOf[item.parent_id]) childrenOf[item.parent_id] = [];
        childrenOf[item.parent_id].push(item.entry_id);
      }
      // Counter per parent
      const counters = {};
      for (const item of treeData) {
        if (!counters[item.parent_id]) counters[item.parent_id] = 0;
        counters[item.parent_id]++;
        const parentNum = numberMap[item.parent_id];
        if (item.type === 'request_list') {
          numberMap[item.entry_id] = '' + counters[item.parent_id];
        } else {
          numberMap[item.entry_id] = (parentNum ? parentNum + '.' : '') + counters[item.parent_id];
        }
      }
    }

    // Check if an item or any ancestor is collapsed
    function isHidden(item) {
      // Walk up parent chain — if any ancestor is collapsed, hide this item
      const parentMap = {};
      for (const t of treeData) parentMap[t.entry_id] = t.parent_id;

      let pid = item.parent_id;
      while (pid && pid !== projectID) {
        if (collapsed.has(pid)) return true;
        pid = parentMap[pid];
      }
      return false;
    }

    function renderTree() {
      const tbody = document.getElementById('treeBody');
      let html = '';
      for (const item of treeData) {
        if (isHidden(item)) continue;
        const d = item.data || {};
        const num = numberMap[item.entry_id] || '';
        const indent = Math.max(0, item.depth - 1) * 20;
        const isCollapsible = item.type === 'request_list' || item.type === 'section';
        const isCollapsed = collapsed.has(item.entry_id);
        const chevron = isCollapsible
          ? `<span class="collapse-btn ${isCollapsed?'collapsed':''}" onclick="toggleCollapse('${item.entry_id}')">\u25BC</span>`
          : '';

        if (item.type === 'request_list') {
          const name = d.name || 'Request List';
          const childCount = item.children_count || 0;
          html += `<tr class="row-list" data-id="${item.entry_id}" data-type="${item.type}" data-parent="${item.parent_id}" data-depth="${item.depth}">
            <td></td>
            <td colspan="9" style="padding-left:${indent+10}px">
              ${chevron}
              <strong style="color:var(--ds-tx);margin-left:4px">${escHtml(name)}</strong>
              <span style="color:var(--ds-tx3);margin-left:8px;font-size:11px">${childCount} items</span>
            </td>
          </tr>`;
        } else if (item.type === 'section') {
          const name = d.name || d.title || 'Section';
          html += `<tr class="row-section" data-id="${item.entry_id}" data-type="${item.type}" data-parent="${item.parent_id}" data-depth="${item.depth}"
                draggable="true" ondragstart="onDragStart(event)" ondragover="onDragOver(event)" ondragleave="onDragLeave(event)" ondrop="onDrop(event)">
            <td class="drag-handle" style="color:var(--ds-tx3);font-size:11px;cursor:grab">\u2630</td>
            <td class="row-num" style="padding-left:${indent}px">${escHtml(num)}</td>
            <td colspan="8" style="padding-left:${indent}px">
              ${chevron}
              <span style="color:var(--ds-tx);font-weight:600;margin-left:4px">${escHtml(name)}</span>
              <span style="color:var(--ds-tx3);margin-left:8px;font-size:11px">${item.children_count||0} requests</span>
            </td>
          </tr>`;
        } else {
          // request row
          const title = d.title || d.description || 'Untitled';
          const buyerComment = d.buyer_comment || '';
          const sellerComment = d.seller_comment || '';
          html += `<tr class="row-request" data-id="${item.entry_id}" data-type="${item.type}" data-parent="${item.parent_id}" data-depth="${item.depth}"
                draggable="true" ondragstart="onDragStart(event)" ondragover="onDragOver(event)" ondragleave="onDragLeave(event)" ondrop="onDrop(event)">
            <td class="drag-handle" style="color:var(--ds-tx3);font-size:11px">\u2630</td>
            <td class="row-num" style="padding-left:${indent}px">${escHtml(num)}</td>
            <td style="white-space:normal;max-width:400px;padding-left:${indent}px">
              <a href="/app/requests/${item.entry_id}" style="color:var(--ds-tx);text-decoration:none" class="hover:underline">${escHtml(title)}</a>
            </td>
            <td>${priorityBadge(d.priority)}</td>
            <td>${statusBadge(d.status)}</td>
            <td style="text-align:center">
              ${item.answer_count > 0
                ? `<span class="badge" style="background:rgba(74,222,128,.15);color:#4ade80;cursor:pointer" onclick="showAttachModal('${item.entry_id}','${escHtml(title)}')">${item.answer_count}</span>`
                : `<span style="color:var(--ds-tx3);cursor:pointer;font-size:12px" onclick="showAttachModal('${item.entry_id}','${escHtml(title)}')">&mdash;</span>`}
            </td>
            <td style="max-width:140px;overflow:hidden;text-overflow:ellipsis;color:var(--ds-tx2);font-size:12px" title="${escHtml(buyerComment)}">${escHtml(buyerComment)}</td>
            <td style="max-width:140px;overflow:hidden;text-overflow:ellipsis;color:var(--ds-tx2);font-size:12px" title="${escHtml(sellerComment)}">${escHtml(sellerComment)}</td>
            <td style="color:var(--ds-tx3);font-size:12px">${fmtDate(item.created_at)}</td>
            <td style="position:relative">
              <button onclick="toggleMenu(event,'${item.entry_id}')" style="background:none;border:none;cursor:pointer;color:var(--ds-tx3);font-size:16px;padding:2px 6px">&hellip;</button>
              <div id="menu-${item.entry_id}" class="actions-menu" style="display:none">
                <button onclick="showAttachModal('${item.entry_id}','${escHtml(title)}')">Attach Answer</button>
                <button onclick="deleteEntry('${item.entry_id}')">Delete</button>
              </div>
            </td>
          </tr>`;
        }
      }
      if (!html) html = '<tr><td colspan="10" class="text-[#94a3b8] text-sm py-4">No requests found.</td></tr>';
      tbody.innerHTML = html;
    }

    function toggleCollapse(id) {
      if (collapsed.has(id)) collapsed.delete(id); else collapsed.add(id);
      renderTree();
    }

    // ---- Actions menu ----
    function toggleMenu(e, id) {
      e.stopPropagation();
      // Close any open menu
      if (openMenuId && openMenuId !== id) {
        const prev = document.getElementById('menu-' + openMenuId);
        if (prev) prev.style.display = 'none';
      }
      const menu = document.getElementById('menu-' + id);
      if (menu) {
        menu.style.display = menu.style.display === 'none' ? 'block' : 'none';
        openMenuId = menu.style.display === 'block' ? id : null;
      }
    }
    document.addEventListener('click', () => {
      if (openMenuId) {
        const m = document.getElementById('menu-' + openMenuId);
        if (m) m.style.display = 'none';
        openMenuId = null;
      }
    });

    async function deleteEntry(entryID) {
      if (!confirm('Delete this entry?')) return;
      await fetchAPI('/api/projects/' + projectID + '/entries/' + entryID, { method: 'DELETE' });
      loadRequestTree();
    }

    // ---- Drag & Drop ----
    let dragEntryId = null;

    function onDragStart(e) {
      dragEntryId = e.currentTarget.dataset.id;
      e.dataTransfer.effectAllowed = 'move';
      e.currentTarget.style.opacity = '0.5';
    }

    function onDragOver(e) {
      e.preventDefault();
      e.dataTransfer.dropEffect = 'move';
      const tr = e.currentTarget;
      // Remove all drop indicators
      tr.classList.remove('drop-above', 'drop-below', 'drop-into');
      const rect = tr.getBoundingClientRect();
      const y = e.clientY - rect.top;
      const pct = y / rect.height;
      if (tr.dataset.type === 'section' && pct > 0.25 && pct < 0.75) {
        tr.classList.add('drop-into');
      } else if (pct < 0.5) {
        tr.classList.add('drop-above');
      } else {
        tr.classList.add('drop-below');
      }
    }

    function onDragLeave(e) {
      e.currentTarget.classList.remove('drop-above', 'drop-below', 'drop-into');
    }

    async function onDrop(e) {
      e.preventDefault();
      const tr = e.currentTarget;
      tr.classList.remove('drop-above', 'drop-below', 'drop-into');
      document.querySelectorAll('#reqTree tr').forEach(r => r.style.opacity = '');

      if (!dragEntryId || dragEntryId === tr.dataset.id) return;

      const targetId = tr.dataset.id;
      const targetType = tr.dataset.type;
      const rect = tr.getBoundingClientRect();
      const y = e.clientY - rect.top;
      const pct = y / rect.height;

      let newParentId, position;

      if (targetType === 'section' && pct > 0.25 && pct < 0.75) {
        // Drop INTO section — make it last child
        newParentId = targetId;
        const children = treeData.filter(t => t.parent_id === targetId);
        position = children.length;
      } else {
        // Drop BEFORE or AFTER — same parent as target
        newParentId = tr.dataset.parent;
        const siblings = treeData.filter(t => t.parent_id === newParentId);
        const targetIdx = siblings.findIndex(s => s.entry_id === targetId);
        position = pct < 0.5 ? targetIdx : targetIdx + 1;
      }

      try {
        await fetchAPI('/api/projects/' + projectID + '/entries/' + dragEntryId + '/move', {
          method: 'POST',
          body: JSON.stringify({ parent_id: newParentId, position })
        });
        await loadRequestTree();
      } catch(e) {
        console.error('Move failed:', e);
      }
      dragEntryId = null;
    }

    // ---- Attach answer modal ----
    function showAttachModal(reqId, reqTitle) {
      attachRequestId = reqId;
      document.getElementById('attachReqTitle').textContent = reqTitle;
      document.getElementById('attachModal').style.display = 'flex';
      document.getElementById('attachSearch').value = '';
      document.getElementById('attachFile').value = '';
      loadAnswersForPicker('');
      // Also load existing links
      loadLinkedAnswers(reqId);
    }
    function closeAttachModal() { document.getElementById('attachModal').style.display = 'none'; attachRequestId = null; }

    let searchTimeout;
    function searchAnswers(q) {
      clearTimeout(searchTimeout);
      searchTimeout = setTimeout(() => loadAnswersForPicker(q), 200);
    }

    async function loadAnswersForPicker(q) {
      const list = document.getElementById('attachList');
      try {
        const res = await fetchAPI('/api/projects/' + projectID + '/answers?q=' + encodeURIComponent(q));
        const answers = await res.json();
        if (!answers || answers.length === 0) {
          list.innerHTML = '<div class="text-[#94a3b8] text-sm py-2">No documents found.</div>';
          return;
        }
        list.innerHTML = answers.map(a => {
          const d = a.data || {};
          const name = d.filename || d.name || d.title || 'Document';
          return `<div class="flex items-center justify-between px-3 py-2 rounded-lg hover:bg-white/[0.04] transition">
            <span class="text-white text-sm truncate flex-1">${escHtml(name)}</span>
            <button onclick="linkAnswer('${a.entry_id}')" class="ml-2 px-3 py-1 bg-[#c9a84c]/20 text-[#c9a84c] rounded text-xs font-medium hover:bg-[#c9a84c]/30 transition">Link</button>
          </div>`;
        }).join('');
      } catch(e) {
        list.innerHTML = '<div class="text-red-400 text-sm py-2">Failed to load.</div>';
      }
    }

    async function loadLinkedAnswers(reqId) {
      try {
        const res = await fetchAPI('/api/projects/' + projectID + '/requests/' + reqId + '/links');
        const links = await res.json();
        if (links && links.length > 0) {
          const linkedHtml = links.map(l => {
            const d = l.data || {};
            const name = d.filename || d.name || 'Document';
            return `<div class="flex items-center justify-between px-3 py-2 rounded-lg bg-green-500/5 border border-green-500/10">
              <span class="text-green-300 text-sm truncate flex-1">${escHtml(name)}</span>
              <button onclick="unlinkAnswer('${l.answer_id}')" class="ml-2 px-3 py-1 bg-red-500/20 text-red-300 rounded text-xs font-medium hover:bg-red-500/30 transition">Unlink</button>
            </div>`;
          }).join('');
          const list = document.getElementById('attachList');
          list.innerHTML = '<div class="text-[#94a3b8] text-xs font-medium mb-1 mt-1">LINKED</div>' + linkedHtml + '<div class="border-t border-white/[0.08] my-2"></div><div class="text-[#94a3b8] text-xs font-medium mb-1">AVAILABLE</div>' + list.innerHTML;
        }
      } catch(e) {}
    }

    async function linkAnswer(answerId) {
      if (!attachRequestId) return;
      await fetchAPI('/api/projects/' + projectID + '/requests/' + attachRequestId + '/links', {
        method: 'POST', body: JSON.stringify({ answer_id: answerId })
      });
      closeAttachModal();
      loadRequestTree();
    }

    async function unlinkAnswer(answerId) {
      if (!attachRequestId) return;
      await fetchAPI('/api/projects/' + projectID + '/requests/' + attachRequestId + '/links/' + answerId, { method: 'DELETE' });
      // Refresh the modal
      showAttachModal(attachRequestId, document.getElementById('attachReqTitle').textContent);
    }

    async function uploadAndLink() {
      const fileInput = document.getElementById('attachFile');
      const file = fileInput.files[0];
      if (!file || !attachRequestId) return;

      // 1. Upload file
      const fd = new FormData();
      fd.append('file', file);
      const uploadRes = await fetch('/api/projects/' + projectID + '/objects', {
        method: 'POST', headers: { 'Authorization': 'Bearer ' + token }, body: fd
      });
      const uploadData = await uploadRes.json();
      if (!uploadRes.ok) { alert('Upload failed'); return; }

      // 2. Create answer entry
      const answerData = JSON.stringify({ filename: file.name, object_id: uploadData.object_id, name: file.name });
      const entryRes = await fetchAPI('/api/projects/' + projectID + '/entries', {
        method: 'POST',
        body: JSON.stringify({ project_id: projectID, parent_id: projectID, type: 'answer', depth: 1, data: answerData, stage: 'dataroom' })
      });
      const entry = await entryRes.json();

      // 3. Link it
      if (entry.entry_id) {
        await fetchAPI('/api/projects/' + projectID + '/requests/' + attachRequestId + '/links', {
          method: 'POST', body: JSON.stringify({ answer_id: entry.entry_id })
        });
      }

      closeAttachModal();
      loadRequestTree();
    }

    // ---- Orgs / Team ----
    async function loadOrgs() {
      try {
        const res = await fetchAPI('/api/projects/' + projectID + '/orgs');
        const orgs = await res.json();
        const list = document.getElementById('orgList');
        if (!orgs || orgs.length === 0) { list.innerHTML = '<div class="text-[#94a3b8] text-sm">No organizations added yet.</div>'; return; }
        list.innerHTML = orgs.map(o => {
          const d = parseData(o.data_text);
          const rc = roleColors[d.role] || 'bg-gray-500/20 text-gray-300';
          return `<div class="flex items-center gap-4 px-5 py-4 rounded-xl bg-[#0d1f3c] border border-white/[0.08]">
            <div class="flex-1">
              <div class="flex items-center gap-2 mb-1">
                <span class="text-white font-medium">${escHtml(d.org_name || d.name || 'Unknown')}</span>
                <span class="px-2 py-0.5 rounded-full text-xs font-medium capitalize ${rc}">${d.role || '?'}</span>
              </div>
              ${d.domains ? `<div class="flex gap-1.5 flex-wrap">${(Array.isArray(d.domains)?d.domains:[d.domains]).map(dm=>`<span class="text-xs text-[#94a3b8] font-mono bg-white/[0.05] px-2 py-0.5 rounded">@${dm}</span>`).join('')}</div>` : ''}
            </div>
          </div>`;
        }).join('');
      } catch(e) {}
    }

    async function loadTeam() {
      try {
        const res = await fetchAPI('/api/projects/' + projectID + '/members');
        const members = await res.json();
        const list = document.getElementById('teamList');
        if (!members || members.length === 0) { list.innerHTML = '<div class="text-[#94a3b8] text-sm">No team members yet.</div>'; return; }
        list.innerHTML = members.map(m => `
          <div class="flex items-center gap-4 px-5 py-3 rounded-xl bg-[#0d1f3c] border border-white/[0.08]">
            <div class="w-8 h-8 rounded-full bg-[#c9a84c]/20 flex items-center justify-center text-[#c9a84c] font-semibold text-sm">${(m.name||m.email||'?')[0].toUpperCase()}</div>
            <div class="flex-1">
              <div class="text-white text-sm font-medium">${escHtml(m.name || m.email)}</div>
              ${m.name ? `<div class="text-[#94a3b8] text-xs">${escHtml(m.email)}</div>` : ''}
            </div>
            <span class="text-xs text-[#94a3b8] capitalize">${m.role || 'member'}</span>
          </div>`).join('');
      } catch(e) {}
    }

    function switchTab(name, el) {
      document.querySelectorAll('.tab').forEach(t => { t.classList.remove('active','text-white'); t.classList.add('text-[#94a3b8]'); });
      el.classList.add('active','text-white'); el.classList.remove('text-[#94a3b8]');
      document.getElementById('tab-requests').classList.toggle('hidden', name !== 'requests');
      document.getElementById('tab-orgs').classList.toggle('hidden', name !== 'orgs');
      document.getElementById('tab-team').classList.toggle('hidden', name !== 'team');
      if (name === 'orgs') loadOrgs();
      if (name === 'team') loadTeam();
    }

    // ---- Import ----
    function openImportModal() {
      document.getElementById('importModal').style.display='flex';
      document.getElementById('importFile').value='';
      document.getElementById('importListName').value='';
      document.getElementById('importError').classList.add('hidden');
    }
    function closeImportModal() { document.getElementById('importModal').style.display='none'; }

    async function submitImport() {
      const file = document.getElementById('importFile').files[0];
      const errEl = document.getElementById('importError');
      const btn = document.getElementById('importBtn');
      if (!file) { errEl.textContent = 'Please select a file'; errEl.classList.remove('hidden'); return; }
      btn.disabled = true; btn.textContent = 'Importing...'; errEl.classList.add('hidden');
      const fd = new FormData();
      fd.append('file', file);
      fd.append('mode', document.getElementById('importMode').value);
      fd.append('list_name', document.getElementById('importListName').value);
      try {
        const res = await fetch('/api/projects/' + projectID + '/requests/import', { method: 'POST', headers: { 'Authorization': 'Bearer ' + token }, body: fd });
        const data = await res.json();
        if (!res.ok) throw new Error(data.error || 'Import failed');
        closeImportModal();
        loadRequestTree();
      } catch(e) { errEl.textContent = e.message; errEl.classList.remove('hidden'); }
      finally { btn.disabled = false; btn.textContent = 'Import'; }
    }

    // ---- Init ----
    loadProject();
    loadRequestTree();
  </script>
  <div id="ds-theme-bar">
    <button data-t="midnight" onclick="setTheme('midnight')">Midnight</button>
    <button data-t="light" onclick="setTheme('light')">Light</button>
    <button data-t="slate" onclick="setTheme('slate')">Slate</button>
    <button data-t="compact" onclick="setTheme('compact')">Compact</button>
    <button data-t="executive" onclick="setTheme('executive')">Executive</button>
  </div>
  <script>
  function setTheme(t){document.documentElement.setAttribute('data-theme',t);localStorage.setItem('ds_theme',t);document.querySelectorAll('#ds-theme-bar button').forEach(b=>b.classList.toggle('active',b.getAttribute('data-t')===t))}
  setTheme(localStorage.getItem('ds_theme')||'midnight');
  </script>
</body>
</html>
