// Messages for the OAuth bounce-back flag (/?email=...). The server keeps the
// real failure reason in its own log on purpose (it can contain provider
// details) — the browser only ever sees these generic outcomes.
const OAUTH_RESULT_MESSAGES = {
    connected: { kind: 'success', text: 'Mailbox connected.' },
    declined:  { kind: 'hint',    text: 'Connection cancelled — nothing was linked.' },
    error:     { kind: 'error',   text: 'Connecting your mailbox failed on the server. ' +
                 'Ask an admin to check the server log — common causes are covered in docs/EMAIL_SETUP.md.' },
};

// Email settings body — connect/disconnect the user's mailbox + the org-wide
// "never log" exclusion list. Sole home: Settings → Email (all roles) — the
// nav envelope modal retired 2026-08-02, and the OAuth bounce-back now lands
// here via SettingsView's initialSection. Filename is legacy; renaming would
// just churn index.html's script tag for no behavior change.
const EmailSettingsBody = ({ currentUser, tenant, oauthResult }) => {
    const [status, setStatus]         = React.useState(null);   // null = loading
    const [exclusions, setExclusions] = React.useState([]);
    const [newPattern, setNewPattern] = React.useState('');
    const [newNote, setNewNote]       = React.useState('');
    const [error, setError]           = React.useState('');
    const [busy, setBusy]             = React.useState(false);
    const [syncResult, setSyncResult] = React.useState(null); // { logged, scanned } after Sync now
    // Deliverability acknowledgment (Community plan) — per-user, persisted via
    // the settings whitelist; optimistic apply with rollback like Preferences.
    const [deliverAck, setDeliverAck] = React.useState(!!currentUser.settings?.email_deliverability_ack);

    const isManager = currentUser.role === 'manager' || currentUser.role === 'admin';
    const oauthMsg  = OAUTH_RESULT_MESSAGES[oauthResult] || null;
    // Same display convention as IntegrationsSection: entitlements === null
    // renders unlocked (the server is the real gate either way).
    const features       = tenant?.entitlements?.features;
    const platformLocked = !!(features && features['email.platform'] !== true);

    const handleAckChange = (checked) => {
        setDeliverAck(checked);
        api.updateMySettings({ email_deliverability_ack: checked })
            .catch(() => setDeliverAck(!checked)); // rollback — the checkbox never lies about saved state
    };

    const load = () => {
        api.getEmailStatus().then(setStatus).catch(e => setError(e.message));
        api.getEmailExclusions().then(setExclusions).catch(() => {});
    };
    React.useEffect(load, []);

    const handleConnect = async (provider) => {
        setBusy(true); setError('');
        try {
            const { url } = await api.getEmailConnectUrl(provider);
            // Full-window redirect: Microsoft's consent page bounces back to
            // /api/email/callback, which lands the user back in the app.
            window.location.href = url;
        } catch (e) { setError(e.message); setBusy(false); }
    };

    const handleSyncNow = async () => {
        setBusy(true); setError(''); setSyncResult(null);
        try {
            setSyncResult(await api.syncEmailNow());
            load(); // refresh last_synced_at / any error surfaced on the connection
        } catch (e) { setError(e.message); }
        setBusy(false);
    };

    const handleDisconnect = async () => {
        if (!window.confirm('Disconnect this mailbox? The CRM forgets its access; you can also revoke it from your Microsoft account.')) return;
        setBusy(true); setError('');
        try { await api.disconnectEmail(); load(); } catch (e) { setError(e.message); }
        setBusy(false);
    };

    const handleAddExclusion = async (e) => {
        e.preventDefault();
        if (!newPattern.trim()) return;
        setError('');
        try {
            await api.addEmailExclusion(newPattern.trim(), newNote.trim() || undefined);
            setNewPattern(''); setNewNote('');
            api.getEmailExclusions().then(setExclusions);
        } catch (err) { setError(err.message); }
    };

    const conn = status?.connection;
    const providers = status?.configured_providers || [];

    return (
        <div>
            {oauthMsg && (
                <div className={oauthMsg.kind === 'error' ? 'api-error' : oauthMsg.kind === 'success' ? 'api-success' : 'note-box'}
                     style={{ marginBottom: '1rem' }}>
                    {oauthMsg.text}
                </div>
            )}
            {error && <div className="api-error">{error}</div>}

            <h3 style={{ marginTop: 0 }}>Your mailbox</h3>
            {status === null ? (
                <p>Loading…</p>
            ) : conn ? (
                <div>
                    <p>
                        <i className="fas fa-check-circle" style={{ color: 'var(--success, #16a34a)' }}></i>{' '}
                        Connected: <strong>{conn.email_address}</strong> ({conn.provider})
                        {conn.status !== 'active' && <span> — status: {conn.status}</span>}
                    </p>
                    {conn.last_synced_at && (
                        <p className="form-hint">Last synced: {new Date(conn.last_synced_at).toLocaleString()}</p>
                    )}
                    {conn.last_error && <p className="form-hint">Last error: {conn.last_error}</p>}
                    {syncResult && (
                        <p className="form-hint">
                            {syncResult.skipped
                                ? 'A sync is already running — try again in a moment.'
                                : `Sync complete: ${syncResult.scanned} new message${syncResult.scanned === 1 ? '' : 's'} checked, ${syncResult.logged} logged to contacts.`}
                        </p>
                    )}
                    <div style={{ display: 'flex', gap: '0.5rem' }}>
                        <button className="btn btn-primary" onClick={handleSyncNow} disabled={busy}>
                            <i className="fas fa-sync-alt"></i> Sync now
                        </button>
                        <button className="btn btn-secondary" onClick={handleDisconnect} disabled={busy}>
                            Disconnect
                        </button>
                    </div>
                </div>
            ) : providers.length === 0 ? (
                <p className="form-hint">
                    No mail provider is configured on this server yet — an admin needs to set the
                    provider keys in <code>.env</code> (see <code>docs/EMAIL_SETUP.md</code>).
                </p>
            ) : (
                <div>
                    <p className="form-hint">
                        Connect your mailbox so the CRM can send email as you and (soon) log
                        customer conversations automatically. Only mail matching CRM contacts
                        is ever kept.
                    </p>
                    {providers.includes('microsoft') && (
                        <button className="btn btn-primary" onClick={() => handleConnect('microsoft')} disabled={busy}>
                            <i className="fab fa-microsoft"></i> Connect Microsoft / Outlook
                        </button>
                    )}
                    {providers.includes('google') && (
                        <button className="btn btn-primary" onClick={() => handleConnect('google')} disabled={busy}
                            style={{ marginLeft: providers.includes('microsoft') ? '0.5rem' : 0 }}>
                            <i className="fab fa-google"></i> Connect Google / Gmail
                        </button>
                    )}
                </div>
            )}

            {platformLocked && (
                <div className="note-box" style={{ marginTop: '1.25rem' }}>
                    <strong>Email on the Community plan</strong>
                    <p className="form-hint" style={{ marginTop: '0.5rem' }}>
                        Community workspaces send customer email through the mailbox you connect
                        above — your address, your sent folder. Managed delivery on the platform's
                        sending domain is part of the paid plans.
                    </p>
                    <p className="form-hint">
                        Before relying on it for customer email, set up your domain for email
                        authentication with your mail provider: <strong>SPF</strong>, <strong>DKIM</strong>,
                        and <strong>DMARC</strong>. Mail from a domain without these — or without any
                        sending reputation — is frequently filtered to spam.
                    </p>
                    <label style={{ display: 'flex', gap: '0.5rem', alignItems: 'flex-start', marginTop: '0.5rem', cursor: 'pointer' }}>
                        <input type="checkbox" checked={deliverAck}
                               onChange={e => handleAckChange(e.target.checked)}
                               style={{ marginTop: '0.2rem' }} />
                        <span className="form-hint">
                            I understand that if I send from my own mailbox without proper domain
                            setup (SPF, DKIM, DMARC) and sender reputation, my email will likely
                            go to spam.
                        </span>
                    </label>
                    <details style={{ marginTop: '0.5rem' }}>
                        <summary style={{ cursor: 'pointer' }}>More on email deliverability</summary>
                        <ul className="form-hint" style={{ marginTop: '0.5rem', paddingLeft: '1.25rem' }}>
                            <li style={{ marginBottom: '0.35rem' }}>
                                <strong>SPF</strong> lists which servers may send for your domain,{' '}
                                <strong>DKIM</strong> cryptographically signs your mail, and{' '}
                                <strong>DMARC</strong> tells receiving servers what to do when those
                                checks fail. Microsoft 365 and Google Workspace both have a guided
                                domain-setup page that configures all three.
                            </li>
                            <li style={{ marginBottom: '0.35rem' }}>
                                Google's sender guidelines (the rules Gmail enforces):{' '}
                                <a href="https://support.google.com/a/answer/81126" target="_blank" rel="noopener">support.google.com/a/answer/81126</a>
                            </li>
                            <li style={{ marginBottom: '0.35rem' }}>
                                Microsoft's email-authentication overview:{' '}
                                <a href="https://learn.microsoft.com/en-us/defender-office-365/email-authentication-about" target="_blank" rel="noopener">learn.microsoft.com — email authentication</a>
                            </li>
                            <li>
                                DMARC.org's plain-English overview:{' '}
                                <a href="https://dmarc.org/overview/" target="_blank" rel="noopener">dmarc.org/overview</a>
                            </li>
                        </ul>
                    </details>
                </div>
            )}

            <hr style={{ margin: '1.25rem 0' }} />

            <h3>Never-log list</h3>
            <p className="form-hint">
                Mail to or from these domains/addresses is never logged, even when it matches a
                contact. Your own company domain belongs here.
            </p>
            {exclusions.length === 0
                ? <p className="form-hint"><em>Nothing excluded yet.</em></p>
                : (
                    <ul style={{ listStyle: 'none', padding: 0 }}>
                        {exclusions.map(x => (
                            <li key={x.id} style={{ display: 'flex', alignItems: 'center', gap: '0.5rem', padding: '0.25rem 0' }}>
                                <code>{x.pattern}</code>
                                {x.note && <span className="form-hint">— {x.note}</span>}
                                {isManager && (
                                    <button className="btn-icon" title="Remove"
                                        onClick={() => api.removeEmailExclusion(x.id).then(() => api.getEmailExclusions().then(setExclusions))}>
                                        <i className="fas fa-times"></i>
                                    </button>
                                )}
                            </li>
                        ))}
                    </ul>
                )}
            {isManager && (
                <form onSubmit={handleAddExclusion} style={{ display: 'flex', gap: '0.5rem', marginTop: '0.5rem' }}>
                    <input className="form-input" placeholder="example.com or person@example.com"
                        value={newPattern} onChange={e => setNewPattern(e.target.value)} />
                    <input className="form-input" placeholder="note (optional)"
                        value={newNote} onChange={e => setNewNote(e.target.value)} />
                    <button className="btn btn-secondary" type="submit">Add</button>
                </form>
            )}
        </div>
    );
};
