// Settings → Project Space — the status page the platform operator publishes
// into this workspace (migration 0053). Read-only content for everyone; the
// one tenant-side lever is the admin's viewer picker: which teammates can
// open this page (admins always can).
//
// Rendering: the page is operator-authored HTML shown inside a SANDBOXED
// iframe (sandbox="" — no scripts run, no same-origin access). The sandbox is
// browser-enforced, so even a script tag in the content is inert; we never
// innerHTML it into the app itself.

const CollabSection = ({ currentUser }) => {
    const [data, setData]     = React.useState(null);   // GET /api/collab payload
    const [users, setUsers]   = React.useState(null);   // admin: tenant user list for the picker
    const [picked, setPicked] = React.useState([]);     // staged viewer ids
    const [saving, setSaving] = React.useState(false);
    const [saved, setSaved]   = React.useState(false);
    const [error, setError]   = React.useState(null);

    const isAdmin = currentUser.role === 'admin';

    React.useEffect(() => {
        api.getCollab()
            .then(d => { setData(d); setPicked(d.viewers || []); })
            .catch(err => setError(err.message));
        if (isAdmin) api.getUsers().then(setUsers).catch(() => {});
    }, []);

    const toggle = (id) => {
        setSaved(false);
        setPicked(p => p.includes(id) ? p.filter(x => x !== id) : [...p, id]);
    };

    const saveViewers = async () => {
        setSaving(true); setError(null); setSaved(false);
        try {
            const r = await api.setCollabViewers(picked);
            setPicked(r.viewers);
            setSaved(true);
        } catch (err) {
            setError(err.message);
        } finally {
            setSaving(false);
        }
    };

    if (error && !data) return <p style={{ color: 'var(--danger)', fontSize: '0.875rem' }}>{error}</p>;
    if (!data) return <p style={{ color: 'var(--text-3)', fontSize: '0.875rem' }}>Loading…</p>;

    // Admins with nothing published yet get an honest empty state; anyone
    // else without access shouldn't normally land here (the card is hidden),
    // but say something sane if they do.
    if (!data.can_view) {
        return <p style={{ color: 'var(--text-3)', fontSize: '0.875rem' }}>This page hasn't been shared with you.</p>;
    }

    const dirty = data.viewers && JSON.stringify([...picked].sort()) !== JSON.stringify([...(data.viewers || [])].sort());
    // Admins always see the page — the picker is for everyone else.
    const pickable = (users || []).filter(u => u.role !== 'admin' && u.is_active);

    return (
        <div className="settings-form">
            {data.published ? (
                <>
                    <p style={{ fontSize: '0.8125rem', color: 'var(--text-3)', marginBottom: '0.5rem' }}>
                        <strong style={{ color: 'var(--text-1)' }}>{data.doc.title}</strong>
                        {' · '}updated {new Date(data.doc.updated_at).toLocaleDateString()} — published by your service provider.
                    </p>
                    <iframe
                        sandbox=""
                        srcDoc={data.doc.html}
                        title={data.doc.title}
                        style={{ width: '100%', height: '70vh', border: '1px solid var(--border)',
                                 borderRadius: '8px', background: '#fff' }}
                    />
                </>
            ) : (
                <p style={{ fontSize: '0.875rem', color: 'var(--text-3)' }}>
                    Nothing has been published to your Project Space yet — updates from your
                    service provider will appear here.
                </p>
            )}

            {isAdmin && (
                <div style={{ marginTop: '1.25rem' }}>
                    <h4 style={{ marginBottom: '0.35rem' }}>Who can see this page</h4>
                    <p style={{ fontSize: '0.8125rem', color: 'var(--text-3)', marginBottom: '0.5rem' }}>
                        Admins always can. Pick any teammates who should too — everyone else
                        won't even see the card.
                    </p>
                    {!data.published ? (
                        <p style={{ fontSize: '0.8125rem', color: 'var(--text-3)' }}>Sharing opens up once something is published.</p>
                    ) : !users ? (
                        <p style={{ fontSize: '0.8125rem', color: 'var(--text-3)' }}>Loading teammates…</p>
                    ) : pickable.length === 0 ? (
                        <p style={{ fontSize: '0.8125rem', color: 'var(--text-3)' }}>No non-admin teammates yet.</p>
                    ) : (
                        <>
                            {/* House rule: chips, never checkbox lists */}
                            <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.4rem', marginBottom: '0.6rem' }}>
                                {pickable.map(u => (
                                    <button
                                        key={u.id}
                                        type="button"
                                        className={`filter-chip ${picked.includes(u.id) ? 'active' : ''}`}
                                        onClick={() => toggle(u.id)}
                                    >
                                        {u.first_name} {u.last_name}
                                    </button>
                                ))}
                            </div>
                            <div style={{ display: 'flex', gap: '0.6rem', alignItems: 'center' }}>
                                <button className="btn btn-primary" disabled={saving || !dirty} onClick={saveViewers}>
                                    {saving ? <><i className="fas fa-spinner fa-spin"></i> Saving…</> : 'Save sharing'}
                                </button>
                                {saved && !dirty && (
                                    <span style={{ fontSize: '0.8125rem', color: 'var(--text-3)' }}>
                                        <i className="fas fa-check" style={{ color: 'var(--success)' }}></i> Saved
                                    </span>
                                )}
                            </div>
                        </>
                    )}
                    {error && <p style={{ color: 'var(--danger)', fontSize: '0.875rem', marginTop: '0.5rem' }}>{error}</p>}
                </div>
            )}
        </div>
    );
};
