import { api } from '../api.js';
import { showToast } from '../components/toast.js';
const API = (url, opts = {}) => fetch('/api' + url, { headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${localStorage.getItem('token')}`, ...opts.headers }, ...opts }).then(r => r.json());
export async function render(container) {
const hash = window.location.hash;
if (hash.startsWith('#/team/')) {
const id = hash.split('#/team/')[1];
return renderTeamDetail(container, id);
}
return renderList(container);
}
async function renderList(container) {
container.innerHTML = `
`;
document.getElementById('newTeamBtn').onclick = async () => {
const name = prompt('Team name:');
if (!name) return;
const team = await API('/teams', { method: 'POST', body: JSON.stringify({ name }) });
window.location.hash = `#/team/${team.id}`;
};
try {
const teams = await API('/teams');
const list = document.getElementById('teamsList');
if (!teams.length) {
list.innerHTML = 'No teams yet
Create a team to share devices with other users.
';
return;
}
list.innerHTML = `
${teams.map(t => `
${t.name[0].toUpperCase()}
${t.name}
Your role: ${t.my_role} · ${t.member_count} member(s)
`).join('')}
`;
} catch (err) { showToast(err.message, 'error'); }
}
async function renderTeamDetail(container, teamId) {
let team, devices, allDevices;
try {
[team, devices, allDevices] = await Promise.all([
API(`/teams/${teamId}`),
API(`/teams/${teamId}/devices`),
api.getDevices()
]);
} catch { container.innerHTML = 'Team not found
'; return; }
const unassignedDevices = allDevices.filter(d => !d.team_id || d.team_id !== teamId);
container.innerHTML = `
Back to Teams
Members (${team.members?.length || 0})
${(team.members || []).map(m => `
${(m.user_name || m.email)[0].toUpperCase()}
${m.user_name || m.email}
${m.email}
${m.role !== 'owner' ? `
` : ''}
`).join('') || '
No members yet
'}
Shared Devices (${devices.length})
${devices.map(d => `
`).join('') || '
No devices shared with this team
'}
`;
// Invite member
document.getElementById('inviteMemberBtn').onclick = async () => {
const email = prompt('Email address to invite:');
if (!email) return;
const role = prompt('Role (viewer, editor, or owner):', 'editor');
if (!['viewer', 'editor', 'owner'].includes(role)) { showToast('Invalid role', 'error'); return; }
try {
await API(`/teams/${teamId}/invite`, { method: 'POST', body: JSON.stringify({ email, role }) });
showToast('Invitation sent', 'success');
renderTeamDetail(container, teamId);
} catch (err) { showToast(err.message, 'error'); }
};
// Change member role
container.querySelectorAll('[data-member-id]').forEach(select => {
select.onchange = async () => {
try {
await API(`/teams/${teamId}/members/${select.dataset.memberId}`, { method: 'PUT', body: JSON.stringify({ role: select.value }) });
showToast('Role updated', 'success');
} catch (err) { showToast(err.message, 'error'); }
};
});
// Remove member
container.querySelectorAll('[data-remove-member]').forEach(btn => {
btn.onclick = async () => {
try {
await API(`/teams/${teamId}/members/${btn.dataset.removeMember}`, { method: 'DELETE' });
showToast('Member removed', 'success');
renderTeamDetail(container, teamId);
} catch (err) { showToast(err.message, 'error'); }
};
});
// Add device to team
document.getElementById('addDeviceToTeam').onchange = async (e) => {
const deviceId = e.target.value;
if (!deviceId) return;
try {
await API(`/teams/${teamId}/devices`, { method: 'POST', body: JSON.stringify({ device_id: deviceId }) });
showToast('Device added to team', 'success');
renderTeamDetail(container, teamId);
} catch (err) { showToast(err.message, 'error'); }
};
// Remove device from team
container.querySelectorAll('[data-remove-device]').forEach(btn => {
btn.onclick = async () => {
try {
await API(`/teams/${teamId}/devices/${btn.dataset.removeDevice}`, { method: 'DELETE' });
showToast('Device removed from team', 'success');
renderTeamDetail(container, teamId);
} catch (err) { showToast(err.message, 'error'); }
};
});
// Delete team
document.getElementById('deleteTeamBtn').onclick = async () => {
try {
await API(`/teams/${teamId}`, { method: 'DELETE' });
showToast('Team deleted', 'success');
window.location.hash = '#/teams';
} catch (err) { showToast(err.message, 'error'); }
};
}
export function cleanup() {}