// Quick email — one-off compose opened by clicking any email address on an
// account. Sends from the rep's OWN connected mailbox (routes/emails.js owns
// the why) and auto-logs to the comms feed. Only reachable when a mailbox is
// connected — AccountDetailView keeps the mailto: fallback otherwise.
//
// "Use a template instead" hands off to TemplateSendModal via onUseTemplate —
// the two composes stay separate components on purpose (template sends are
// merge-field/policy machinery; this is deliberately just a letter).
//
// replyTo (optional) turns this into a REPLY rather than a new message: pass
// { communicationId, subject, quote? } and the compose prefills a "Re:" subject
// and the quoted original, and the server threads it (routes/emails.js resolves
// the communication id to the real Message-ID — the client never supplies mail
// headers). Same component on purpose: a reply IS just a letter with context.
const QuickEmailModal = ({ account, toEmail, contactId = null, contactName = null, replyTo = null, onSent, onClose, onUseTemplate }) => {
    // "Re:" once, never "Re: Re:" — mail clients already stack those and it
    // reads as amateur.
    const initialSubject = replyTo
        ? (/^re:/i.test((replyTo.subject || '').trim())
            ? replyTo.subject.trim()
            : `Re: ${(replyTo.subject || '').trim()}`).slice(0, 200)
        : '';
    // Quoted original, plain text, attribution line first — the convention every
    // mail client uses. Left editable: it's the rep's letter, not ours.
    const initialBody = replyTo?.quote
        ? `\n\n${replyTo.quote.split('\n').map(l => `> ${l}`).join('\n')}`
        : '';

    const [subject, setSubject] = React.useState(initialSubject);
    const [body, setBody]       = React.useState(initialBody);
    const [sending, setSending] = React.useState(false);
    const [error, setError]     = React.useState(null);

    const handleSend = async () => {
        setSending(true); setError(null);
        try {
            await api.sendQuickEmail({
                account_id: account.id,
                contact_id: contactId,
                to: toEmail,
                subject,
                body,
                in_reply_to: replyTo?.communicationId || undefined,
            });
            onSent && onSent();
            onClose();
        } catch (err) { setError(err.message); }
        finally { setSending(false); }
    };

    return (
        <Modal isOpen={true} title={replyTo ? 'Reply' : 'New Email'} onClose={onClose}>
            <div className="form-group">
                <label className="form-label">To</label>
                <div className="form-input" style={{ background: 'var(--bg-2, transparent)', color: 'var(--text-2)' }}>
                    {contactName ? `${contactName} — ${toEmail}` : toEmail}
                </div>
            </div>
            <div className="form-group">
                <label className="form-label">Subject</label>
                <input className="form-input" value={subject} maxLength={200} autoFocus={!replyTo}
                       onChange={e => setSubject(e.target.value)} />
            </div>
            <div className="form-group">
                <label className="form-label">Message</label>
                <textarea className="form-input" rows={8} value={body} maxLength={20000} autoFocus={!!replyTo}
                          onChange={e => setBody(e.target.value)} style={{ resize: 'vertical' }} />
            </div>

            <p style={{ fontSize: '0.72rem', color: 'var(--text-3)', marginTop: '-0.25rem' }}>
                <i className="fas fa-paper-plane" style={{ marginRight: '0.3rem' }}></i>
                Sends from your connected mailbox and logs to this account's activity feed.
            </p>

            {error && <p style={{ color: 'var(--danger, #dc2626)', fontSize: '0.8125rem' }}>{error}</p>}

            <div style={{ display: 'flex', gap: '0.75rem', alignItems: 'center', marginTop: '1rem' }}>
                {onUseTemplate && (
                    <button className="btn btn-secondary btn-small" onClick={onUseTemplate}>
                        <i className="fas fa-file-alt"></i> Use a template instead
                    </button>
                )}
                <div style={{ marginLeft: 'auto', display: 'flex', gap: '0.75rem' }}>
                    <button className="btn btn-secondary btn-small" onClick={onClose}>Cancel</button>
                    <button className="btn btn-primary btn-small" disabled={sending || !subject.trim() || !body.trim()}
                            onClick={handleSend}>
                        {sending ? <><i className="fas fa-spinner fa-spin"></i> Sending…</> : <><i className="fas fa-paper-plane"></i> Send</>}
                    </button>
                </div>
            </div>
        </Modal>
    );
};
