/**
 * Team Admin > Settings
 */
const { html } = window;
const { useState, useEffect, useCallback } = hooks;

export default function SettingsSection({ teamId }) {
    const [team, setTeam] = useState(null);
    const [name, setName] = useState('');
    const [description, setDescription] = useState('');
    const [loading, setLoading] = useState(true);
    const [saving, setSaving] = useState(false);

    const load = useCallback(async () => {
        try {
            const data = await sw.api.teams.get(teamId);
            setTeam(data);
            setName(data.name || '');
            setDescription(data.description || '');
        } catch (e) { sw.toast(e.message, 'error'); }
        finally { setLoading(false); }
    }, [teamId]);

    useEffect(() => { load(); }, [load]);

    async function save() {
        setSaving(true);
        try {
            await sw.api.teams.update(teamId, {
                name: name.trim(),
                description: description.trim(),
            });
            sw.toast('Settings saved', 'success');
        } catch (e) { sw.toast(e.message, 'error'); }
        finally { setSaving(false); }
    }

    if (loading) return html`<div class="settings-placeholder">Loading\u2026</div>`;

    return html`
        <div class="admin-settings-form">
            <div class="settings-section">
                <h3>Team Details</h3>
                <div class="form-group">
                    <label>Team Name</label>
                    <input value=${name} onInput=${e => setName(e.target.value)} placeholder="My Team" />
                </div>
                <div class="form-group">
                    <label>Description</label>
                    <textarea rows="3" value=${description}
                              onInput=${e => setDescription(e.target.value)}
                              placeholder="Optional description\u2026"></textarea>
                </div>
            </div>

            ${team && html`
                <div class="settings-section">
                    <h3>Info</h3>
                    <div class="text-muted" style="font-size:12px;">
                        <div>ID: ${team.id}</div>
                        ${team.created_at && html`<div>Created: ${new Date(team.created_at).toLocaleString()}</div>`}
                        ${team.member_count != null && html`<div>Members: ${team.member_count}</div>`}
                    </div>
                </div>
            `}

            <div style="display:flex;gap:8px;align-items:center;margin-top:16px;">
                <button class="btn-md btn-primary" onClick=${save} disabled=${saving}>${saving ? 'Saving\u2026' : 'Save Settings'}</button>
            </div>
        </div>
    `;
}
