import { useState, useEffect } from 'react';
import { api } from '../utils/api.js';
import { useToast } from '../contexts/ToastContext.jsx';
// ── Helpers ───────────────────────────────────────────────────────────────────
const APP_TYPES = {
'RosterChirp-Chat': { label: 'RosterChirp-Chat', desc: 'Chat only. No Branding, Group Manager or Schedule Manager.' },
'RosterChirp-Brand': { label: 'RosterChirp-Brand', desc: 'Chat and Branding.' },
'RosterChirp-Team': { label: 'RosterChirp-Team', desc: 'Chat, Branding, Group Manager and Schedule Manager.' },
};
// ── Toggle switch ─────────────────────────────────────────────────────────────
function Toggle({ checked, onChange }) {
return (
onChange(!checked)}
role="switch"
aria-checked={checked}
style={{
width: 44, height: 24, borderRadius: 12, cursor: 'pointer', flexShrink: 0,
background: checked ? 'var(--primary)' : 'var(--border)',
position: 'relative', transition: 'background 0.2s',
}}
>
);
}
// ── Messages Tab ──────────────────────────────────────────────────────────────
function MessagesTab() {
const toast = useToast();
const [settings, setSettings] = useState({
msgPublic: true,
msgGroup: true,
msgPrivateGroup: true,
msgU2U: true,
});
const [saving, setSaving] = useState(false);
useEffect(() => {
api.getSettings().then(({ settings: s }) => {
setSettings({
msgPublic: s.feature_msg_public !== 'false',
msgGroup: s.feature_msg_group !== 'false',
msgPrivateGroup: s.feature_msg_private_group !== 'false',
msgU2U: s.feature_msg_u2u !== 'false',
});
}).catch(() => {});
}, []);
const toggle = (key) => setSettings(prev => ({ ...prev, [key]: !prev[key] }));
const handleSave = async () => {
setSaving(true);
try {
await api.updateMessageSettings(settings);
toast('Message settings saved', 'success');
window.dispatchEvent(new Event('rosterchirp:settings-changed'));
} catch (e) { toast(e.message, 'error'); }
finally { setSaving(false); }
};
const rows = [
{ key: 'msgPublic', label: 'Public Messages', desc: 'Public group channels visible to all members.' },
{ key: 'msgGroup', label: 'Group Messages', desc: 'Private group messages managed by User Groups.' },
{ key: 'msgPrivateGroup', label: 'Private Group Messages', desc: 'Private multi-member group conversations.' },
{ key: 'msgU2U', label: 'Private Messages (U2U)', desc: 'One-on-one direct messages between users.' },
];
return (
Message Features
Disable a feature to hide it from all menus, sidebars, and modals.
{rows.map((r, i) => (
))}
);
}
// ── Team Management Tab ───────────────────────────────────────────────────────
function TeamManagementTab() {
const toast = useToast();
const [userGroups, setUserGroups] = useState([]);
const [toolManagers, setToolManagers] = useState([]);
const [saving, setSaving] = useState(false);
useEffect(() => {
api.getUserGroups().then(({ groups }) => setUserGroups([...(groups||[])].sort((a, b) => a.name.localeCompare(b.name)))).catch(() => {});
api.getSettings().then(({ settings }) => {
// Read from unified key, fall back to legacy key
setToolManagers(JSON.parse(settings.team_tool_managers || settings.team_group_managers || '[]'));
}).catch(() => {});
}, []);
const toggle = (id) => {
setToolManagers(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id]);
};
const handleSave = async () => {
setSaving(true);
try {
await api.updateTeamSettings({ toolManagers });
toast('Team settings saved', 'success');
window.dispatchEvent(new Event('rosterchirp:settings-changed'));
} catch (e) { toast(e.message, 'error'); }
finally { setSaving(false); }
};
return (
Tool Managers
Members of selected groups can access Group Manager, Schedule Manager, and User Manager. Admin users always have access to all three tools.
{userGroups.length === 0 ? (
No user groups created yet. Create groups in the Group Manager first.
) : (
{userGroups.map(g => (
))}
)}
{toolManagers.length === 0 && (
No groups selected — tools are admin-only.
)}
);
}
// ── Login Type Tab ────────────────────────────────────────────────────────────
const LOGIN_TYPE_OPTIONS = [
{
id: 'all_ages',
label: 'Unrestricted',
desc: 'No age restrictions. All users interact normally. Default behaviour.',
},
{
id: 'guardian_only',
label: 'Guardian Only',
desc: "Parents are required to add their child's details in their profile. They respond on behalf of the child for events with availability tracking for the players group.",
},
{
id: 'mixed_age',
label: 'Restricted',
desc: "Parents, or user managers, add the minor's user account to their guardian profile. Minor aged users cannot login until a manager approves the guardian link.",
},
];
function LoginTypeTab() {
const toast = useToast();
const [loginType, setLoginType] = useState('all_ages');
const [playersGroupId, setPlayersGroupId] = useState('');
const [guardiansGroupId,setGuardiansGroupId] = useState('');
const [userGroups, setUserGroups] = useState([]);
const [canChange, setCanChange] = useState(false);
const [saving, setSaving] = useState(false);
useEffect(() => {
Promise.all([api.getSettings(), api.getUserGroups()]).then(([{ settings: s }, { groups }]) => {
setLoginType(s.feature_login_type || 'all_ages');
setPlayersGroupId(s.feature_players_group_id || '');
setGuardiansGroupId(s.feature_guardians_group_id || '');
setUserGroups([...(groups || [])].sort((a, b) => a.name.localeCompare(b.name)));
}).catch(() => {});
// Determine if the user table is empty enough to allow changes
api.getUsers().then(({ users }) => {
const nonAdmins = (users || []).filter(u => u.role !== 'admin');
setCanChange(nonAdmins.length === 0);
}).catch(() => {});
}, []);
const handleSave = async () => {
setSaving(true);
try {
await api.updateLoginType({
loginType,
playersGroupId: playersGroupId ? parseInt(playersGroupId) : null,
guardiansGroupId: guardiansGroupId ? parseInt(guardiansGroupId) : null,
});
toast('Login Type settings saved', 'success');
window.dispatchEvent(new Event('rosterchirp:settings-changed'));
} catch (e) { toast(e.message, 'error'); }
finally { setSaving(false); }
};
const needsGroups = loginType !== 'all_ages';
return (
Login Type
{/* Warning */}
⚠️
This setting can only be set or changed when the user table is empty (no non-admin users exist).
{/* Options */}
{/* Group selectors — only shown for Guardian Only / Mixed Age */}
{needsGroups && (
The user group that children / aliases are added to.
Members of this group see the "Add Child" option in their profile.
)}
);
}
// ── Registration Tab ──────────────────────────────────────────────────────────
function RegistrationTab({ onFeaturesChanged }) {
const toast = useToast();
const [settings, setSettings] = useState({});
const [regCode, setRegCode] = useState('');
const [regLoading, setRegLoading] = useState(false);
const [copied, setCopied] = useState(false);
useEffect(() => {
api.getSettings().then(({ settings }) => setSettings(settings)).catch(() => {});
}, []);
const appType = settings.app_type || 'RosterChirp-Chat';
const activeCode = settings.registration_code || '';
const adminEmail = settings.admin_email || '—';
// Placeholder serial number derived from hostname
const serialNumber = btoa(window.location.hostname).replace(/[^A-Z0-9]/gi, '').toUpperCase().slice(0, 16).padEnd(16, '0');
const handleCopySerial = async () => {
await navigator.clipboard.writeText(serialNumber).catch(() => {});
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
const handleRegister = async () => {
if (!regCode.trim()) return toast('Enter a registration code', 'error');
setRegLoading(true);
try {
const { features: f } = await api.registerCode(regCode.trim());
setRegCode('');
const fresh = await api.getSettings();
setSettings(fresh.settings);
toast('Registration applied successfully.', 'success');
window.dispatchEvent(new Event('rosterchirp:settings-changed'));
onFeaturesChanged && onFeaturesChanged(f);
} catch (e) { toast(e.message || 'Invalid registration code', 'error'); }
finally { setRegLoading(false); }
};
const handleClear = async () => {
try {
const { features: f } = await api.registerCode('');
const fresh = await api.getSettings();
setSettings(fresh.settings);
toast('Registration cleared.', 'success');
window.dispatchEvent(new Event('rosterchirp:settings-changed'));
onFeaturesChanged && onFeaturesChanged(f);
} catch (e) { toast(e.message, 'error'); }
};
const typeInfo = APP_TYPES[appType] || APP_TYPES['RosterChirp-Chat'];
const siteUrl = window.location.origin;
return (
{/* Info box */}
Registration {activeCode ? 'is' : 'required:'}
RosterChirp {activeCode ? 'is' : 'will be'} registered to:
Type: {typeInfo.label}
URL: {siteUrl}
{/* Type */}
Application Type
{typeInfo.label}
{typeInfo.desc}
{/* Serial Number */}
{/* Registration Code */}
{activeCode && (
Registered — {typeInfo.label}
)}
Registration codes unlock application features. Contact your RosterChirp provider for a code.
);
}
// ── Main modal ────────────────────────────────────────────────────────────────
export default function SettingsModal({ onClose, onFeaturesChanged }) {
const [tab, setTab] = useState('messages');
const [appType, setAppType] = useState('RosterChirp-Chat');
useEffect(() => {
api.getSettings().then(({ settings }) => {
setAppType(settings.app_type || 'RosterChirp-Chat');
}).catch(() => {});
const handler = () => api.getSettings().then(({ settings }) => setAppType(settings.app_type || 'RosterChirp-Chat')).catch(() => {});
window.addEventListener('rosterchirp:settings-changed', handler);
return () => window.removeEventListener('rosterchirp:settings-changed', handler);
}, []);
const isTeam = appType === 'RosterChirp-Team';
return (
e.target === e.currentTarget && onClose()}>
Settings
{/* Select navigation */}
{tab === 'messages' &&
}
{tab === 'team' &&
}
{tab === 'login-type' &&
}
{tab === 'registration' &&
}
);
}