// Workspace management UI component
export function init({ apiFetch, container, onSwitch }) {
  let workspaces = [];
  let activeId = 'default';

  async function loadWorkspaces() {
    try {
      const res = await apiFetch('/api/workspaces');
      workspaces = await res.json();
      activeId = (workspaces.find(w => w.is_active) || {}).id || 'default';
    } catch { workspaces = []; }
    render();
  }

  async function createWorkspace() {
    const name = prompt('New workspace name:');
    if (!name || !name.trim()) return;
    try {
      await apiFetch('/api/workspaces', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: name.trim(), displayName: name.trim() })
      });
      await loadWorkspaces();
    } catch (err) { console.error('Failed to create workspace:', err); }
  }

  async function switchWorkspace(id) {
    try {
      await apiFetch(`/api/workspaces/${encodeURIComponent(id)}/activate`, { method: 'PUT' });
      await loadWorkspaces();
      if (onSwitch) onSwitch(id);
    } catch (err) { console.error('Failed to switch workspace:', err); }
  }

  async function deleteWorkspace(id) {
    if (id === 'default') return;
    if (!confirm(`Delete workspace "${id}"? Files will not be removed.`)) return;
    try {
      await apiFetch(`/api/workspaces/${encodeURIComponent(id)}`, { method: 'DELETE' });
      await loadWorkspaces();
    } catch (err) { console.error('Failed to delete workspace:', err); }
  }

  async function loadFiles() {
    try {
      const res = await apiFetch('/api/workspace-files');
      return await res.json();
    } catch { return []; }
  }

  function render() {
    container.innerHTML = `
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;">
        <h2 style="color:var(--accent);font-size:16px;margin:0;">Workspaces</h2>
        <button id="ws-create-btn" style="background:var(--accent);color:#fff;border:none;padding:6px 14px;border-radius:6px;font-size:12px;cursor:pointer;font-family:var(--mono);">+ New Workspace</button>
      </div>
      <div id="ws-list">${workspaces.map(renderCard).join('')}</div>
      <div style="margin-top:24px;">
        <h3 style="font-size:11px;color:var(--text-dim);text-transform:uppercase;letter-spacing:1px;margin-bottom:8px;">Files in Active Workspace</h3>
        <div id="ws-files-list" style="color:var(--text-dim);font-size:12px;">Loading...</div>
      </div>
    `;

    container.querySelector('#ws-create-btn')?.addEventListener('click', createWorkspace);
    container.querySelectorAll('[data-ws-switch]').forEach(btn =>
      btn.addEventListener('click', () => switchWorkspace(btn.dataset.wsSwitch)));
    container.querySelectorAll('[data-ws-delete]').forEach(btn =>
      btn.addEventListener('click', () => deleteWorkspace(btn.dataset.wsDelete)));

    loadFiles().then(files => {
      const el = container.querySelector('#ws-files-list');
      if (!el) return;
      if (!files.length) { el.textContent = 'No files yet'; return; }
      el.innerHTML = files.map(f => {
        const size = f.size < 1024 ? `${f.size}B` : f.size < 1048576 ? `${(f.size/1024).toFixed(1)}KB` : `${(f.size/1048576).toFixed(1)}MB`;
        return `<div style="padding:4px 0;border-bottom:1px solid var(--border);display:flex;justify-content:space-between;">
          <span style="color:var(--text);">${f.name}</span>
          <span style="color:var(--text-dim);font-size:10px;">${size}</span>
        </div>`;
      }).join('');
    });
  }

  function renderCard(ws) {
    const isActive = ws.is_active || ws.id === activeId;
    return `<div style="background:var(--bg2);border:1px solid ${isActive ? 'var(--accent)' : 'var(--border)'};border-radius:6px;padding:12px;margin-bottom:8px;">
      <div style="display:flex;justify-content:space-between;align-items:center;">
        <div>
          <span style="color:${isActive ? 'var(--accent)' : 'var(--text)'};font-weight:600;">${ws.name || ws.id}</span>
          ${isActive ? '<span style="background:var(--accent);color:#000;font-size:9px;padding:2px 6px;border-radius:8px;margin-left:8px;font-weight:700;">ACTIVE</span>' : ''}
        </div>
        <div style="display:flex;gap:6px;">
          ${!isActive ? `<button data-ws-switch="${ws.id}" style="background:none;border:1px solid var(--accent);color:var(--accent);padding:3px 10px;border-radius:4px;font-size:11px;cursor:pointer;font-family:var(--mono);">Switch</button>` : ''}
          ${ws.id !== 'default' ? `<button data-ws-delete="${ws.id}" style="background:none;border:1px solid var(--red);color:var(--red);padding:3px 10px;border-radius:4px;font-size:11px;cursor:pointer;font-family:var(--mono);">Delete</button>` : ''}
        </div>
      </div>
      ${ws.description ? `<div style="color:var(--text-dim);font-size:11px;margin-top:4px;">${ws.description}</div>` : ''}
    </div>`;
  }

  loadWorkspaces();
  return { refresh: loadWorkspaces };
}
