// What's New at login: shows curated release notes (src/data/whatsnew.json)
// the user hasn't seen yet, tracked via users.settings.last_seen_version.
// The json is the single source of truth for both the notes and the beta
// flag — the login screen's BETA badge reads the same file.

// Numeric semver compare: -1 / 0 / 1. Both inputs are trusted x.y.z strings
// (the json is ours; the settings value is validated server-side).
const compareVersions = (a, b) => {
    const pa = a.split('.').map(Number);
    const pb = b.split('.').map(Number);
    for (let i = 0; i < 3; i++) {
        if (pa[i] !== pb[i]) return pa[i] < pb[i] ? -1 : 1;
    }
    return 0;
};

const WhatsNewModal = ({ currentUser }) => {
    const [notes, setNotes] = React.useState(null); // { beta, betaNotice, entries: [...] } once loaded
    const [dismissed, setDismissed] = React.useState(false);

    React.useEffect(() => {
        fetch('/src/data/whatsnew.json')
            .then(r => r.ok ? r.json() : null)
            .then(data => { if (data?.entries?.length) setNotes(data); })
            .catch(() => {}); // release notes are decoration — never block the app over them
    }, []);

    if (!notes || dismissed) return null;

    const lastSeen = currentUser.settings?.last_seen_version;
    const newest = notes.entries[0].version;
    if (lastSeen && compareVersions(newest, lastSeen) <= 0) return null;

    // First-time users get only the latest entry (no history dump); returning
    // users get everything that shipped since they last dismissed, capped so
    // a long-absent user isn't scrolled into next week.
    const unseen = lastSeen
        ? notes.entries.filter(e => compareVersions(e.version, lastSeen) > 0).slice(0, 3)
        : notes.entries.slice(0, 1);

    const dismiss = () => {
        setDismissed(true);
        // Fire-and-forget: a failed save just means the modal shows again
        // next login — annoying, not harmful.
        api.updateMySettings({ last_seen_version: newest }).catch(() => {});
    };

    return (
        <Modal isOpen={true} onClose={dismiss} title="What's New">
            <div className="whatsnew-body">
                {unseen.map(entry => (
                    <div key={entry.version} className="whatsnew-entry">
                        <div className="whatsnew-entry-header">
                            <span className="whatsnew-version">v{entry.version}</span>
                            <span className="whatsnew-title">{entry.title}</span>
                        </div>
                        <ul>
                            {entry.items.map((item, i) => <li key={i}>{item}</li>)}
                        </ul>
                    </div>
                ))}

                {notes.beta && (
                    <div className="whatsnew-beta-notice">
                        <i className="fas fa-flask"></i> <strong>Beta:</strong> {notes.betaNotice}
                    </div>
                )}

                <div className="whatsnew-actions">
                    <button className="btn btn-primary" onClick={dismiss}>Got it</button>
                </div>
            </div>
        </Modal>
    );
};
