// daygig-projects.js — Projects, events, campaigns sub-tabs

// ── Projects ──────────────────────────────────────────────────────────────
  function toggleProjForm() {
    const body = document.getElementById('projFormBody');
    if (!body) return;
    const visible = body.style.display !== 'none';
    body.style.display = visible ? 'none' : 'block';
    if (!visible) document.getElementById('proj-name').focus();
  }

  async function loadProjects() {
    const status = document.getElementById('proj-filter-status')?.value || '';
    const ptype  = document.getElementById('proj-filter-type')?.value  || '';
    const qs     = new URLSearchParams();
    if (status) qs.set('status', status);
    if (ptype)  qs.set('project_type', ptype);
    try {
      const res  = await fetch('/api/projects?' + qs.toString());
      const data = await res.json();
      const tbody = document.getElementById('proj-tbody');
      const sub   = document.getElementById('proj-list-sub');
      if (!tbody) return;
      if (sub) sub.textContent = `${data.total || 0} project${data.total !== 1 ? 's' : ''}`;
      const rows = data.projects || [];
      if (rows.length === 0) {
        tbody.innerHTML = '<tr><td colspan="7" style="text-align:center;color:var(--text-muted);padding:24px;">No projects found.</td></tr>';
        return;
      }
      const statusColor = { active:'var(--pos)', planning:'var(--warn-amber)', paused:'#888', completed:'var(--info)', archived:'#555' };
      const typeLabel = { film:'Film', album:'Album', comic:'Comic', tour:'Tour',
        convention:'Convention', merch_drop:'Merch Drop', kickstarter:'Kickstarter',
        client_work:'Client Work', general:'General' };
      tbody.innerHTML = rows.map(p => `
        <tr>
          <td><strong>${p.name}</strong>${p.notes ? '<br><span style="font-size:11px;color:var(--text-muted);">'+p.notes+'</span>' : ''}</td>
          <td style="font-size:12px;">${typeLabel[p.project_type] || p.project_type}</td>
          <td><span style="font-size:11px;font-family:var(--mono);color:${statusColor[p.status]||'#888'};text-transform:uppercase;">${p.status}</span></td>
          <td style="font-family:var(--mono);font-size:12px;">${p.start_date || '—'}</td>
          <td style="font-family:var(--mono);font-size:12px;">${p.end_date   || '—'}</td>
          <td style="text-align:right;font-family:var(--mono);">${p.budget_cents > 0 ? dgMoney(p.budget||0) : '—'}</td>
          <td style="text-align:right;">
            <button class="btn btn-ghost btn-sm" onclick="archiveProject(${p.id},'${p.name.replace(/'/g,"\'")}')" title="Archive">Archive</button>
          </td>
        </tr>
      `).join('');
    } catch (e) { console.warn('Could not load projects:', e); }
  }

  async function submitProject() {
    const msg  = document.getElementById('proj-msg');
    const name = document.getElementById('proj-name').value.trim();
    if (!name) {
      msg.textContent = 'Project name is required.';
      msg.style.color = 'var(--neg)';
      msg.style.display = 'inline';
      return;
    }
    msg.textContent = 'Saving…';
    msg.style.color = 'var(--text-muted)';
    msg.style.display = 'inline';
    try {
      const res = await fetch('/api/projects', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name,
          project_type: document.getElementById('proj-type').value,
          status:       document.getElementById('proj-status').value,
          start_date:   document.getElementById('proj-start').value || null,
          end_date:     document.getElementById('proj-end').value   || null,
          budget:       document.getElementById('proj-budget').value || 0,
          notes:        document.getElementById('proj-notes').value.trim() || null,
        }),
      });
      const data = await res.json();
      if (data.id) {
        msg.textContent = '✓ Saved';
        msg.style.color = 'var(--pos)';
        // Clear form fields
        ['proj-name','proj-start','proj-end','proj-budget','proj-notes'].forEach(id => {
          document.getElementById(id).value = '';
        });
        document.getElementById('proj-type').value   = 'general';
        document.getElementById('proj-status').value = 'planning';
        setTimeout(() => { msg.style.display = 'none'; toggleProjForm(); }, 1200);
        loadProjects();
      } else {
        msg.textContent = data.error || data.detail || 'Save failed.';
        msg.style.color = 'var(--neg)';
      }
    } catch (e) {
      msg.textContent = 'Network error: ' + e.message;
      msg.style.color = 'var(--neg)';
    }
  }

  async function archiveProject(id, name) {
    if (!confirm(`Archive project "${name}"? It will be hidden from the list but not deleted.`)) return;
    try {
      const res  = await fetch(`/api/projects/archive/${id}`, { method: 'POST' });
      const data = await res.json();
      if (data.id) loadProjects();
      else alert(data.error || 'Archive failed.');
    } catch (e) { alert('Network error: ' + e.message); }
  }