import { api } from '../api.js';
import { showToast } from '../components/toast.js';
import { t, tn } from '../i18n.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(t('team.prompt_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 = `${t('team.empty_title')}
${t('team.empty_desc')}
`;
return;
}
list.innerHTML = `
${teams.map(team => `
${team.name[0].toUpperCase()}
${team.name}
${t('team.your_role', { role: team.my_role })} · ${tn('team.member_count', team.member_count)}
`).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 = `${t('team.not_found')}
`; return; }
const unassignedDevices = allDevices.filter(d => !d.team_id || d.team_id !== teamId);
container.innerHTML = `
${t('team.back')}
${t('team.members_count', { n: 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('') || `
${t('team.no_members')}
`}
${t('team.shared_devices', { n: devices.length })}
${devices.map(d => `
`).join('') || `
${t('team.no_devices')}
`}
`;
document.getElementById('inviteMemberBtn').onclick = async () => {
const email = prompt(t('team.prompt_email'));
if (!email) return;
const role = prompt(t('team.prompt_role'), 'editor');
if (!['viewer', 'editor', 'owner'].includes(role)) { showToast(t('team.toast.invalid_role'), 'error'); return; }
try {
await API(`/teams/${teamId}/invite`, { method: 'POST', body: JSON.stringify({ email, role }) });
showToast(t('team.toast.invitation_sent'), 'success');
renderTeamDetail(container, teamId);
} catch (err) { showToast(err.message, 'error'); }
};
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(t('team.toast.role_updated'), 'success');
} catch (err) { showToast(err.message, 'error'); }
};
});
container.querySelectorAll('[data-remove-member]').forEach(btn => {
btn.onclick = async () => {
try {
await API(`/teams/${teamId}/members/${btn.dataset.removeMember}`, { method: 'DELETE' });
showToast(t('team.toast.member_removed'), 'success');
renderTeamDetail(container, teamId);
} catch (err) { showToast(err.message, 'error'); }
};
});
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(t('team.toast.device_added'), 'success');
renderTeamDetail(container, teamId);
} catch (err) { showToast(err.message, 'error'); }
};
container.querySelectorAll('[data-remove-device]').forEach(btn => {
btn.onclick = async () => {
try {
await API(`/teams/${teamId}/devices/${btn.dataset.removeDevice}`, { method: 'DELETE' });
showToast(t('team.toast.device_removed'), 'success');
renderTeamDetail(container, teamId);
} catch (err) { showToast(err.message, 'error'); }
};
});
document.getElementById('deleteTeamBtn').onclick = async () => {
try {
await API(`/teams/${teamId}`, { method: 'DELETE' });
showToast(t('team.toast.deleted'), 'success');
window.location.hash = '#/teams';
} catch (err) { showToast(err.message, 'error'); }
};
}
export function cleanup() {}