<!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; }
    .req-row:hover { background: rgba(255,255,255,0.03); }
    .section-header { cursor: pointer; user-select: none; }
    .section-header:hover { background: rgba(255,255,255,0.02); }
    .priority-high { background: #ef444420; color: #f87171; }
    .priority-medium { background: #f59e0b20; color: #fbbf24; }
    .priority-low { background: #22c55e20; color: #4ade80; }
    .status-open { background: #3b82f620; color: #60a5fa; }
    .status-in_progress { background: #f59e0b20; color: #fbbf24; }
    .status-answered { background: #22c55e20; color: #4ade80; }
    .status-not_applicable { background: #6b728020; color: #9ca3af; }
  </style>
</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/tasks" 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-[#b0bec5] 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-[#b0bec5]"></span>
      <button onclick="logout()" class="text-sm text-[#b0bec5] 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-[#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="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-[#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="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-[#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 class="flex-1 p-8 max-w-6xl">
      <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-[#b0bec5] text-sm"></p>
        </div>
        <div class="flex gap-2">
          <button id="importBtn" 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>
          <button id="newRequestBtn" class="px-4 py-2 bg-[#c9a84c] hover:bg-[#b8973f] text-[#0a1628] font-semibold rounded-lg text-sm transition">+ New Request</button>
        </div>
      </div>
      <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-[#b0bec5] transition" onclick="switchTab('orgs', this)">Parties</button>
        <button class="tab pb-3 text-sm font-medium text-[#b0bec5] transition" onclick="switchTab('team', this)">Team</button>
      </div>
      <div id="tab-requests">
        <div id="requestList" class="space-y-4"><div class="text-[#b0bec5] text-sm">Loading requests...</div></div>
        <div id="requestEmpty" class="hidden text-center py-16">
          <div class="text-4xl mb-3">📋</div>
          <h3 class="text-lg font-semibold text-white mb-1">No requests yet</h3>
          <p class="text-[#b0bec5] text-sm mb-4">Import a diligence checklist or create requests manually.</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>
      <div id="tab-orgs" class="hidden">
        <div class="flex justify-between items-center mb-4">
          <p class="text-[#b0bec5] text-sm">Parties involved in this deal.</p>
          <button id="addOrgBtn" class="px-4 py-2 bg-[#c9a84c] hover:bg-[#b8973f] text-[#0a1628] font-semibold rounded-lg text-sm transition">+ Add Party</button>
        </div>
        <div id="orgList" class="space-y-3"><div class="text-[#b0bec5] text-sm">Loading...</div></div>
      </div>
      <div id="tab-team" class="hidden">
        <div class="flex justify-between items-center mb-4">
          <p class="text-[#b0bec5] 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-[#b0bec5] text-sm">Loading...</div></div>
      </div>
    </main>
  </div>
  <div id="importModal" class="hidden fixed inset-0 bg-black/60 flex items-center justify-center z-50">
    <div class="bg-[#0d1f3c] rounded-2xl p-6 w-full max-w-md border border-white/[0.08]">
      <h2 class="text-lg font-semibold text-white mb-4">Import Diligence Checklist</h2>
      <form id="importForm" enctype="multipart/form-data">
        <div class="mb-4">
          <label class="block text-sm text-[#b0bec5] mb-1.5">File (CSV or XLSX)</label>
          <input type="file" id="importFile" name="file" accept=".csv,.xlsx,.xls" required class="w-full px-3 py-2 bg-white/[0.05] border border-white/[0.08] rounded-lg text-white text-sm focus:outline-none focus:border-[#c9a84c]">
        </div>
        <div class="mb-4">
          <label class="block text-sm text-[#b0bec5] mb-1.5">Import Mode</label>
          <select id="importMode" name="mode" class="w-full px-3 py-2 bg-white/[0.05] border border-white/[0.08] rounded-lg text-white text-sm focus:outline-none focus:border-[#c9a84c]">
            <option value="add">Add to existing requests</option>
            <option value="replace">Replace all requests</option>
          </select>
        </div>
        <div class="mb-4">
          <label class="block text-sm text-[#b0bec5] mb-1.5">Section Filter (optional)</label>
          <input type="text" id="sectionFilter" name="section_filter" placeholder="e.g. Financial" class="w-full px-3 py-2 bg-white/[0.05] border border-white/[0.08] rounded-lg text-white text-sm focus:outline-none focus:border-[#c9a84c] placeholder:text-[#8899a6]">
        </div>
        <div class="mb-6">
          <label class="flex items-center gap-2 cursor-pointer">
            <input type="checkbox" id="createWorkstreams" name="create_workstreams" class="rounded border-white/[0.2]">
            <span class="text-sm text-[#b0bec5]">Create workstreams from sections</span>
          </label>
        </div>
        <div class="flex gap-3">
          <button type="button" onclick="closeImportModal()" class="flex-1 px-4 py-2 bg-white/[0.05] hover:bg-white/[0.08] text-white rounded-lg text-sm transition">Cancel</button>
          <button type="submit" id="importSubmitBtn" class="flex-1 px-4 py-2 bg-[#c9a84c] hover:bg-[#b8973f] text-[#0a1628] font-semibold rounded-lg text-sm transition">Import</button>
        </div>
      </form>
    </div>
  </div>
  <!-- Add Org Modal -->
  <div id="addOrgModal" class="hidden fixed inset-0 bg-black/60 flex items-center justify-center z-50" onclick="if(event.target===this)closeAddOrg()">
    <div class="bg-[#0d1f3c] rounded-2xl w-full max-w-2xl border border-white/[0.08] max-h-[90vh] overflow-y-auto">
      <!-- Step 1: Email -->
      <div id="addOrgStep1" class="p-6">
        <h2 class="text-lg font-semibold text-white mb-1">Add Party</h2>
        <p class="text-[#b0bec5] text-sm mb-5">Enter the email address of someone at the organization.</p>
        <div class="flex gap-3">
          <input type="email" id="addOrgEmail" placeholder="e.g. michael@andersongroup.com" class="flex-1 px-4 py-2.5 bg-white/[0.05] border border-white/[0.08] rounded-lg text-white text-sm focus:outline-none focus:border-[#c9a84c] placeholder:text-[#8899a6]" onkeydown="if(event.key==='Enter')scrapeOrg()">
          <button onclick="scrapeOrg()" id="scrapeBtn" class="px-5 py-2.5 bg-[#c9a84c] hover:bg-[#b8973f] text-[#0a1628] font-semibold rounded-lg text-sm transition whitespace-nowrap">Look up</button>
        </div>
        <div id="scrapeError" class="hidden mt-3 text-red-400 text-sm"></div>
        <div id="scrapeLoading" class="hidden mt-4 flex items-center gap-3 text-[#b0bec5] text-sm">
          <svg class="animate-spin w-4 h-4" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"/></svg>
          Scanning website...
        </div>
        <div class="flex justify-end mt-4">
          <button onclick="closeAddOrg()" class="px-4 py-2 text-[#b0bec5] hover:text-white text-sm transition">Cancel</button>
        </div>
      </div>

      <!-- Step 2: Org details (prefilled) -->
      <div id="addOrgStep2" class="hidden p-6">
        <h2 class="text-lg font-semibold text-white mb-4">Organization Details</h2>
        <div class="grid grid-cols-2 gap-4 mb-4">
          <div class="col-span-2">
            <label class="block text-xs text-[#b0bec5] mb-1">Name *</label>
            <input type="text" id="orgName" class="w-full px-3 py-2 bg-white/[0.05] border border-white/[0.08] rounded-lg text-white text-sm focus:outline-none focus:border-[#c9a84c]">
          </div>
          <div class="col-span-2">
            <label class="block text-xs text-[#b0bec5] mb-1">Description</label>
            <textarea id="orgDesc" rows="2" class="w-full px-3 py-2 bg-white/[0.05] border border-white/[0.08] rounded-lg text-white text-sm focus:outline-none focus:border-[#c9a84c] resize-none"></textarea>
          </div>
          <div>
            <label class="block text-xs text-[#b0bec5] mb-1">Role in deal *</label>
            <select id="orgRole" class="w-full px-3 py-2 bg-white/[0.05] border border-white/[0.08] rounded-lg text-white text-sm focus:outline-none focus:border-[#c9a84c]">
              <option value="">Select...</option>
              <option value="seller">Seller</option>
              <option value="buyer">Buyer</option>
              <option value="ib">Investment Bank</option>
              <option value="advisor">Advisor</option>
            </select>
          </div>
          <div>
            <label class="block text-xs text-[#b0bec5] mb-1">Industry</label>
            <input type="text" id="orgIndustry" class="w-full px-3 py-2 bg-white/[0.05] border border-white/[0.08] rounded-lg text-white text-sm focus:outline-none focus:border-[#c9a84c]">
          </div>
          <div>
            <label class="block text-xs text-[#b0bec5] mb-1">Website</label>
            <input type="text" id="orgWebsite" class="w-full px-3 py-2 bg-white/[0.05] border border-white/[0.08] rounded-lg text-white text-sm focus:outline-none focus:border-[#c9a84c]">
          </div>
          <div>
            <label class="block text-xs text-[#b0bec5] mb-1">Phone</label>
            <input type="text" id="orgPhone" class="w-full px-3 py-2 bg-white/[0.05] border border-white/[0.08] rounded-lg text-white text-sm focus:outline-none focus:border-[#c9a84c]">
          </div>
          <div class="col-span-2">
            <label class="block text-xs text-[#b0bec5] mb-1">Address</label>
            <input type="text" id="orgAddress" class="w-full px-3 py-2 bg-white/[0.05] border border-white/[0.08] rounded-lg text-white text-sm focus:outline-none focus:border-[#c9a84c]">
          </div>
          <div>
            <label class="block text-xs text-[#b0bec5] mb-1">City</label>
            <input type="text" id="orgCity" class="w-full px-3 py-2 bg-white/[0.05] border border-white/[0.08] rounded-lg text-white text-sm focus:outline-none focus:border-[#c9a84c]">
          </div>
          <div>
            <label class="block text-xs text-[#b0bec5] mb-1">State</label>
            <input type="text" id="orgState" class="w-full px-3 py-2 bg-white/[0.05] border border-white/[0.08] rounded-lg text-white text-sm focus:outline-none focus:border-[#c9a84c]">
          </div>
          <div>
            <label class="block text-xs text-[#b0bec5] mb-1">Founded</label>
            <input type="text" id="orgFounded" class="w-full px-3 py-2 bg-white/[0.05] border border-white/[0.08] rounded-lg text-white text-sm focus:outline-none focus:border-[#c9a84c]">
          </div>
          <div>
            <label class="block text-xs text-[#b0bec5] mb-1">LinkedIn</label>
            <input type="text" id="orgLinkedIn" class="w-full px-3 py-2 bg-white/[0.05] border border-white/[0.08] rounded-lg text-white text-sm focus:outline-none focus:border-[#c9a84c]">
          </div>
        </div>
        <div class="flex justify-between">
          <button onclick="showAddOrgStep(1)" class="px-4 py-2 text-[#b0bec5] hover:text-white text-sm transition">Back</button>
          <button onclick="showAddOrgStep(3)" class="px-5 py-2 bg-[#c9a84c] hover:bg-[#b8973f] text-[#0a1628] font-semibold rounded-lg text-sm transition">Next: Select People</button>
        </div>
      </div>

      <!-- Step 3: Colleagues -->
      <div id="addOrgStep3" class="hidden p-6">
        <h2 class="text-lg font-semibold text-white mb-1">Select Colleagues</h2>
        <p class="text-[#b0bec5] text-sm mb-4">Choose who to add to this deal. They'll receive an invite email.</p>
        <div class="flex items-center gap-3 mb-4">
          <label class="flex items-center gap-2 cursor-pointer text-sm text-[#b0bec5]">
            <input type="checkbox" id="selectAllPeople" onchange="toggleAllPeople(this.checked)" class="rounded border-white/[0.2] accent-[#c9a84c]">
            Select all
          </label>
          <span id="selectedCount" class="text-xs text-[#8899a6]">0 selected</span>
        </div>
        <div id="peopleList" class="space-y-2 mb-4 max-h-[50vh] overflow-y-auto"></div>
        <div id="noPeople" class="hidden text-[#b0bec5] text-sm py-8 text-center">No team members found on the website.</div>
        <div class="flex justify-between">
          <button onclick="showAddOrgStep(2)" class="px-4 py-2 text-[#b0bec5] hover:text-white text-sm transition">Back</button>
          <button onclick="submitAddOrg()" id="submitOrgBtn" class="px-5 py-2 bg-[#c9a84c] hover:bg-[#b8973f] text-[#0a1628] font-semibold rounded-lg text-sm transition">Add Organization</button>
        </div>
      </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 };
      if (!(opts.body instanceof FormData)) opts.headers['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) { const d = document.createElement('div'); d.textContent = s; return d.innerHTML; }
    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' };
    const expandedSections = new Set();
    async function loadProject() {
      try {
        const res = await fetchAPI('/api/projects/' + projectID + '/detail');
        if (!res.ok) { document.getElementById('projectTitle').textContent = 'Not found'; return; }
        const p = await res.json();
        const proj = p.project;
        const d = parseData(proj.data_text);
        const name = d.name || proj.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) { console.error(e); }
    }
    async function loadRequests() {
      try {
        const res = await fetchAPI('/api/projects/' + projectID + '/requests');
        const items = await res.json();
        const list = document.getElementById('requestList');
        if (!items || items.length === 0) { list.classList.add('hidden'); document.getElementById('requestEmpty').classList.remove('hidden'); return; }
        list.classList.remove('hidden'); document.getElementById('requestEmpty').classList.add('hidden');
        const sections = {};
        for (const r of items) { const sec = r.section || 'Unsorted'; if (!sections[sec]) sections[sec] = []; sections[sec].push(r); }
        const sortedSections = Object.keys(sections).sort();
        list.innerHTML = sortedSections.map(sec => {
          const reqs = sections[sec]; const isExpanded = expandedSections.has(sec);
          const statusCounts = { open: 0, in_progress: 0, answered: 0, not_applicable: 0 };
          reqs.forEach(r => { statusCounts[r.status || 'open']++; });
          return '<div class="border border-white/[0.08] rounded-xl overflow-hidden"><div class="section-header flex items-center justify-between px-5 py-3 bg-[#0d1f3c]" onclick="toggleSection(\'' + escHtml(sec) + '\')"><div class="flex items-center gap-3"><svg class="w-4 h-4 text-[#b0bec5] transition ' + (isExpanded ? 'rotate-90' : '') + '" id="chevron-' + escHtml(sec) + '" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/></svg><span class="text-white font-medium">' + escHtml(sec) + '</span><span class="text-[#b0bec5] text-xs">(' + reqs.length + ' items)</span></div><div class="flex gap-2">' + (statusCounts.open > 0 ? '<span class="px-2 py-0.5 rounded text-xs status-open">' + statusCounts.open + ' open</span>' : '') + (statusCounts.answered > 0 ? '<span class="px-2 py-0.5 rounded text-xs status-answered">' + statusCounts.answered + ' answered</span>' : '') + '</div></div><div id="section-' + escHtml(sec) + '" class="' + (isExpanded ? '' : 'hidden') + '">' + reqs.map(r => '<a href="/app/requests/' + r.entry_id + '" class="req-row flex items-center gap-4 px-5 py-3 border-t border-white/[0.05] transition cursor-pointer"><div class="w-16 shrink-0"><span class="text-xs font-mono text-[#b0bec5]">' + escHtml(r.item_number || '—') + '</span></div><div class="flex-1 min-w-0"><span class="text-white text-sm truncate block">' + escHtml(r.title || 'Untitled') + '</span></div><span class="shrink-0 w-2 h-2 rounded-full ' + (r.priority === 'high' ? 'bg-red-400' : r.priority === 'low' ? 'bg-green-400' : 'bg-yellow-400') + '" title="' + r.priority + ' priority"></span><span class="shrink-0 px-2.5 py-0.5 rounded text-xs font-medium status-' + (r.status || 'open') + '">' + (r.status || 'open').replace('_', ' ') + '</span></a>').join('') + '</div></div>';
        }).join('');
      } catch(e) { console.error(e); document.getElementById('requestList').innerHTML = '<div class="text-red-400 text-sm">Failed to load requests.</div>'; }
    }
    function toggleSection(sec) {
      const el = document.getElementById('section-' + sec); const chevron = document.getElementById('chevron-' + sec);
      if (el.classList.contains('hidden')) { el.classList.remove('hidden'); chevron.classList.add('rotate-90'); expandedSections.add(sec); }
      else { el.classList.add('hidden'); chevron.classList.remove('rotate-90'); expandedSections.delete(sec); }
    }
    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-[#b0bec5] text-sm">No organizations added yet.</div>'; return; }
        list.innerHTML = orgs.map(o => { const rc = roleColors[o.role] || 'bg-gray-500/20 text-gray-300'; const domains = o.org_domains || [];
          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(o.org_name || 'Unknown') + '</span><span class="px-2 py-0.5 rounded-full text-xs font-medium capitalize ' + rc + '">' + (o.role || '?') + '</span>' + (o.domain_lock ? '<span class="px-2 py-0.5 rounded-full text-xs bg-white/[0.05] text-[#b0bec5]">🔒 domain locked</span>' : '') + '</div>' + (domains.length > 0 ? '<div class="flex gap-1.5 flex-wrap">' + domains.map(dm => '<span class="text-xs text-[#b0bec5] font-mono bg-white/[0.05] px-2 py-0.5 rounded">@' + dm + '</span>').join('') + '</div>' : '') + '</div></div>';
        }).join('');
      } catch(e) { console.error(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-[#b0bec5] 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-[#b0bec5] text-xs">' + escHtml(m.email) + '</div>' : '') + '</div><span class="text-xs text-[#b0bec5] capitalize">' + (m.role || 'member') + '</span></div>').join('');
      } catch(e) { console.error(e); }
    }
    function switchTab(name, el) {
      document.querySelectorAll('.tab').forEach(t => { t.classList.remove('active','text-white'); t.classList.add('text-[#b0bec5]'); });
      el.classList.add('active','text-white'); el.classList.remove('text-[#b0bec5]');
      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();
    }
    function openImportModal() { document.getElementById('importModal').classList.remove('hidden'); }
    function closeImportModal() { document.getElementById('importModal').classList.add('hidden'); document.getElementById('importForm').reset(); }
    document.getElementById('importForm').onsubmit = async (e) => {
      e.preventDefault();
      const btn = document.getElementById('importSubmitBtn'); btn.disabled = true; btn.textContent = 'Importing...';
      const formData = new FormData();
      formData.append('file', document.getElementById('importFile').files[0]);
      formData.append('mode', document.getElementById('importMode').value);
      formData.append('section_filter', document.getElementById('sectionFilter').value);
      formData.append('create_workstreams', document.getElementById('createWorkstreams').checked ? 'true' : 'false');
      try {
        const res = await fetch('/api/projects/' + projectID + '/requests/import', { method: 'POST', headers: { 'Authorization': 'Bearer ' + token }, body: formData });
        const data = await res.json();
        if (res.ok) { closeImportModal(); loadRequests(); alert('Imported ' + data.imported + ' requests from ' + (data.sections?.length || 0) + ' sections. ' + (data.skipped || 0) + ' skipped.'); }
        else { alert('Import failed: ' + (data.error || 'Unknown error')); }
      } catch (err) { alert('Import failed: ' + err.message); }
      finally { btn.disabled = false; btn.textContent = 'Import'; }
    };
    document.getElementById('newRequestBtn').onclick = () => {
      const title = prompt('Request title:'); if (!title) return;
      fetchAPI('/api/projects/' + projectID + '/entries', { method: 'POST', body: JSON.stringify({ project_id: projectID, parent_id: projectID, type: 'request', depth: 1, summary: title, data: JSON.stringify({ title: title, status: 'open', priority: 'medium' }), stage: 'pre_dataroom' })
      }).then(r => r.json()).then(d => { if (d.entry_id) window.location.href = '/app/requests/' + d.entry_id; else loadRequests(); });
    };
    document.getElementById('importModal').onclick = (e) => { if (e.target.id === 'importModal') closeImportModal(); };

    // ---- Add Org flow ----
    let scrapedData = null;

    document.getElementById('addOrgBtn').onclick = () => {
      scrapedData = null;
      document.getElementById('addOrgEmail').value = '';
      document.getElementById('scrapeError').classList.add('hidden');
      document.getElementById('scrapeLoading').classList.add('hidden');
      showAddOrgStep(1);
      document.getElementById('addOrgModal').classList.remove('hidden');
      setTimeout(() => document.getElementById('addOrgEmail').focus(), 100);
    };

    function closeAddOrg() { document.getElementById('addOrgModal').classList.add('hidden'); }

    function showAddOrgStep(n) {
      document.getElementById('addOrgStep1').classList.toggle('hidden', n !== 1);
      document.getElementById('addOrgStep2').classList.toggle('hidden', n !== 2);
      document.getElementById('addOrgStep3').classList.toggle('hidden', n !== 3);
      if (n === 3) renderPeople();
    }

    async function scrapeOrg() {
      const email = document.getElementById('addOrgEmail').value.trim();
      if (!email || !email.includes('@')) { document.getElementById('scrapeError').textContent = 'Enter a valid email address.'; document.getElementById('scrapeError').classList.remove('hidden'); return; }
      document.getElementById('scrapeError').classList.add('hidden');
      document.getElementById('scrapeLoading').classList.remove('hidden');
      document.getElementById('scrapeBtn').disabled = true;
      try {
        const res = await fetchAPI('/api/scrape/org', { method: 'POST', body: JSON.stringify({ email }) });
        const data = await res.json();
        if (!res.ok) { throw new Error(data.error || 'Scrape failed'); }
        scrapedData = data;
        // Prefill step 2
        document.getElementById('orgName').value = data.name || '';
        document.getElementById('orgDesc').value = data.description || '';
        document.getElementById('orgIndustry').value = data.industry || '';
        document.getElementById('orgWebsite').value = data.website || '';
        document.getElementById('orgPhone').value = data.phone || '';
        document.getElementById('orgAddress').value = data.address || '';
        document.getElementById('orgCity').value = data.city || '';
        document.getElementById('orgState').value = data.state || '';
        document.getElementById('orgFounded').value = data.founded || '';
        document.getElementById('orgLinkedIn').value = data.linkedin || '';
        showAddOrgStep(2);
      } catch (err) {
        document.getElementById('scrapeError').textContent = err.message;
        document.getElementById('scrapeError').classList.remove('hidden');
      } finally {
        document.getElementById('scrapeLoading').classList.add('hidden');
        document.getElementById('scrapeBtn').disabled = false;
      }
    }

    function renderPeople() {
      const people = scrapedData?.people || [];
      const list = document.getElementById('peopleList');
      const none = document.getElementById('noPeople');
      if (people.length === 0) { list.innerHTML = ''; none.classList.remove('hidden'); return; }
      none.classList.add('hidden');
      list.innerHTML = people.map((p, i) => `
        <label class="flex items-center gap-3 p-3 rounded-xl bg-white/[0.02] border border-white/[0.06] hover:bg-white/[0.04] cursor-pointer transition">
          <input type="checkbox" class="person-cb accent-[#c9a84c] rounded" data-idx="${i}" checked onchange="updateSelectedCount()">
          <div class="w-10 h-10 rounded-full bg-[#0d1f3c] shrink-0 overflow-hidden border border-white/[0.08]">
            ${p.photo ? `<img src="${escHtml(p.photo)}" class="w-full h-full object-cover" onerror="this.style.display='none';this.parentElement.innerHTML='<div class=\\'w-full h-full flex items-center justify-center text-[#c9a84c] font-semibold\\'>${escHtml(p.name[0])}</div>'">` : `<div class="w-full h-full flex items-center justify-center text-[#c9a84c] font-semibold">${escHtml(p.name[0])}</div>`}
          </div>
          <div class="flex-1 min-w-0">
            <div class="flex items-center gap-2">
              <span class="text-white text-sm font-medium">${escHtml(p.name)}</span>
              ${p.title ? `<span class="text-xs text-[#b0bec5]">${escHtml(p.title)}</span>` : ''}
            </div>
            <div class="flex items-center gap-3 text-xs text-[#8899a6]">
              ${p.email ? `<span>${escHtml(p.email)}</span>` : ''}
              ${p.phone ? `<span>${escHtml(p.phone)}</span>` : ''}
            </div>
            ${p.bio ? `<div class="text-xs text-[#8899a6] mt-0.5 truncate">${escHtml(p.bio)}</div>` : ''}
          </div>
        </label>
      `).join('');
      document.getElementById('selectAllPeople').checked = true;
      updateSelectedCount();
    }

    function toggleAllPeople(checked) {
      document.querySelectorAll('.person-cb').forEach(cb => cb.checked = checked);
      updateSelectedCount();
    }

    function updateSelectedCount() {
      const checked = document.querySelectorAll('.person-cb:checked').length;
      const total = document.querySelectorAll('.person-cb').length;
      document.getElementById('selectedCount').textContent = checked + ' of ' + total + ' selected';
      document.getElementById('selectAllPeople').checked = (checked === total);
    }

    async function submitAddOrg() {
      const name = document.getElementById('orgName').value.trim();
      const role = document.getElementById('orgRole').value;
      if (!name) { alert('Organization name is required.'); return; }
      if (!role) { alert('Please select a role for this organization.'); return; }

      const domain = scrapedData?.domain || '';
      const people = scrapedData?.people || [];
      const selectedMembers = [];
      document.querySelectorAll('.person-cb:checked').forEach(cb => {
        const p = people[parseInt(cb.dataset.idx)];
        if (p) selectedMembers.push({ name: p.name, email: p.email || '', title: p.title || '', phone: p.phone || '', photo: p.photo || '', bio: p.bio || '', linkedin: p.linkedin || '' });
      });

      const btn = document.getElementById('submitOrgBtn');
      btn.disabled = true; btn.textContent = 'Adding...';

      try {
        const res = await fetchAPI('/api/projects/' + projectID + '/orgs/add', {
          method: 'POST',
          body: JSON.stringify({
            name,
            domains: domain ? [domain] : [],
            role,
            website: document.getElementById('orgWebsite').value,
            description: document.getElementById('orgDesc').value,
            industry: document.getElementById('orgIndustry').value,
            phone: document.getElementById('orgPhone').value,
            address: document.getElementById('orgAddress').value,
            city: document.getElementById('orgCity').value,
            state: document.getElementById('orgState').value,
            founded: document.getElementById('orgFounded').value,
            linkedin: document.getElementById('orgLinkedIn').value,
            members: selectedMembers,
            domain_lock: true,
          })
        });
        const data = await res.json();
        if (!res.ok) throw new Error(data.error || 'Failed to add organization');
        closeAddOrg();
        loadOrgs();
      } catch (err) { alert(err.message); }
      finally { btn.disabled = false; btn.textContent = 'Add Organization'; }
    }

    loadProject(); loadRequests();
  </script>
</body>
</html>
