// Email Templates — tenant-authored templates with merge fields and the
// personal-note slot. Authoring is admin/manager; reps consume these from
// the Send Email button on an account. Locked templates (the default) can't
// be edited at send time — the anti-copy-paste-XXXX rule made structural.

// Merge-field vocabulary shown as insert chips. Mirrors server/lib/
// emailtemplates.js FIELDS — if that grows, grow this list with it.
const TEMPLATE_FIELDS = [
    { token: 'contact.first_name', label: 'Contact first name' },
    { token: 'contact.full_name',  label: 'Contact full name' },
    { token: 'account.name',       label: 'Account name' },
    { token: 'sender.name',        label: 'Your name' },
    { token: 'sender.first_name',  label: 'Your first name' },
    { token: 'company.name',       label: 'Company name' },
    { token: 'personal_note',      label: 'Personal note slot' },
];

const EMPTY_FORM = { name: '', subject: '', body: '', locked: true };

const EmailTemplatesSection = () => {
    const [templates, setTemplates] = React.useState(null);
    const [editing, setEditing]     = React.useState(null);  // null | 'new' | template obj
    const [form, setForm]           = React.useState(EMPTY_FORM);
    const [saving, setSaving]       = React.useState(false);
    const [error, setError]         = React.useState(null);
    const bodyRef                   = React.useRef(null);

    const load = () => api.getTemplates(true).then(setTemplates).catch(() => setTemplates([]));
    React.useEffect(() => { load(); }, []);

    const startEdit = (t) => {
        setEditing(t);
        setError(null);
        setForm(t === 'new' ? EMPTY_FORM : { name: t.name, subject: t.subject, body: t.body, locked: t.locked });
    };

    // Insert a merge token at the cursor in the body textarea.
    const insertToken = (token) => {
        const el = bodyRef.current;
        const tag = `{{${token}}}`;
        if (!el) { setForm(f => ({ ...f, body: f.body + tag })); return; }
        const start = el.selectionStart ?? form.body.length;
        const end   = el.selectionEnd ?? start;
        const body  = form.body.slice(0, start) + tag + form.body.slice(end);
        setForm(f => ({ ...f, body }));
        // restore focus after React re-renders
        setTimeout(() => { el.focus(); el.selectionStart = el.selectionEnd = start + tag.length; }, 0);
    };

    const handleSave = async (e) => {
        e.preventDefault();
        setSaving(true); setError(null);
        try {
            if (editing === 'new') await api.createTemplate(form);
            else await api.updateTemplate(editing.id, form);
            setEditing(null); setForm(EMPTY_FORM);
            load();
        } catch (err) { setError(err.message); }
        finally { setSaving(false); }
    };

    const handleDelete = async (t) => {
        if (!window.confirm(`Delete template "${t.name}"? Emails already sent stay in the log.`)) return;
        try { await api.deleteTemplate(t.id); load(); } catch (err) { alert(err.message); }
    };

    const toggleActive = async (t) => {
        try { await api.updateTemplate(t.id, { is_active: !t.is_active }); load(); } catch (err) { alert(err.message); }
    };

    if (editing !== null) return (
        <form className="settings-form" onSubmit={handleSave}>
            <div className="form-group">
                <label className="form-label">Template Name</label>
                <input className="form-input" value={form.name} onChange={e => setForm(f => ({ ...f, name: e.target.value }))}
                       placeholder="e.g. Site Live Announcement" required maxLength={100} />
            </div>
            <div className="form-group">
                <label className="form-label">Subject</label>
                <input className="form-input" value={form.subject} onChange={e => setForm(f => ({ ...f, subject: e.target.value }))}
                       placeholder="e.g. {{account.name}} — your website is live!" required maxLength={255} />
            </div>
            <div className="form-group">
                <label className="form-label">Body</label>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.375rem', marginBottom: '0.5rem' }}>
                    {TEMPLATE_FIELDS.map(fld => (
                        <button key={fld.token} type="button" className="btn btn-secondary btn-small"
                                style={{ fontSize: '0.72rem', padding: '0.15rem 0.5rem', borderRadius: '999px' }}
                                title={`Insert {{${fld.token}}}`} onClick={() => insertToken(fld.token)}>
                            {fld.label}
                        </button>
                    ))}
                </div>
                <textarea ref={bodyRef} className="form-input" rows={10} value={form.body}
                          onChange={e => setForm(f => ({ ...f, body: e.target.value }))}
                          placeholder={"Hi {{contact.first_name}},\n\nGreat news — the new website for {{account.name}} is live!\n\n{{personal_note}}\n\nBest,\n{{sender.name}}"}
                          required style={{ fontFamily: 'inherit', resize: 'vertical' }} />
                <p style={{ fontSize: '0.75rem', color: 'var(--text-3)', marginTop: '0.375rem' }}>
                    Merge fields fill in automatically from the account — an email can never go out with a blank.
                    Add the <strong>personal note slot</strong> where a hand-typed line should go; it disappears cleanly when no note is written.
                </p>
            </div>
            <div className="form-group">
                <label className="form-label">Editing at send time</label>
                <div style={{ display: 'flex', gap: '0.5rem' }}>
                    {[[true, 'Locked — personal note only'], [false, 'Editable — template is a starting point']].map(([val, label]) => (
                        <button key={String(val)} type="button"
                                className={`btn btn-small ${form.locked === val ? 'btn-primary' : 'btn-secondary'}`}
                                style={{ borderRadius: '999px' }}
                                onClick={() => setForm(f => ({ ...f, locked: val }))}>
                            {label}
                        </button>
                    ))}
                </div>
                <p style={{ fontSize: '0.75rem', color: 'var(--text-3)', marginTop: '0.375rem' }}>
                    Locked keeps every send on-brand and typo-free — recommended for anything official.
                </p>
            </div>
            {error && <p style={{ color: 'var(--danger, #dc2626)', fontSize: '0.8125rem' }}>{error}</p>}
            <div style={{ display: 'flex', gap: '0.75rem' }}>
                <button type="submit" className="btn btn-primary btn-small" disabled={saving}>
                    {saving ? <><i className="fas fa-spinner fa-spin"></i> Saving…</> : <><i className="fas fa-check"></i> {editing === 'new' ? 'Create Template' : 'Save Changes'}</>}
                </button>
                <button type="button" className="btn btn-secondary btn-small" onClick={() => { setEditing(null); setError(null); }}>Cancel</button>
            </div>
        </form>
    );

    return (
        <div className="settings-form">
            <p style={{ fontSize: '0.875rem', color: 'var(--text-3)', marginBottom: '1.25rem' }}>
                Reusable emails your team sends from any account — merge fields fill themselves, and a
                personal-note slot keeps the human touch without the copy-paste.
            </p>
            <button className="btn btn-primary btn-small" style={{ marginBottom: '1.25rem' }} onClick={() => startEdit('new')}>
                <i className="fas fa-plus"></i> New Template
            </button>
            {templates === null ? (
                <p style={{ color: 'var(--text-3)' }}><i className="fas fa-spinner fa-spin"></i> Loading…</p>
            ) : templates.length === 0 ? (
                <p style={{ color: 'var(--text-3)', fontSize: '0.875rem' }}>No templates yet — create your first one above.</p>
            ) : (
                templates.map(t => (
                    <div key={t.id} className="contact-card" style={{ opacity: t.is_active ? 1 : 0.55 }}>
                        <div className="contact-card-header">
                            <div>
                                <span className="contact-card-name">
                                    {t.name}
                                    {t.locked && <i className="fas fa-lock" title="Locked — note slot only" style={{ fontSize: '0.7rem', marginLeft: '0.5rem', color: 'var(--text-3)' }}></i>}
                                    {t.has_note_slot && <span className="primary-badge" style={{ marginLeft: '0.5rem' }}>note slot</span>}
                                    {!t.is_active && <span style={{ fontSize: '0.72rem', color: 'var(--text-3)', marginLeft: '0.5rem' }}>(inactive)</span>}
                                </span>
                                <div className="contact-card-title">{t.subject}</div>
                            </div>
                            <div className="contact-card-actions">
                                <button className="btn-icon-sm" title="Edit" onClick={() => startEdit(t)}><i className="fas fa-pen"></i></button>
                                <button className="btn-icon-sm" title={t.is_active ? 'Deactivate (hide from picker)' : 'Reactivate'} onClick={() => toggleActive(t)}>
                                    <i className={`fas ${t.is_active ? 'fa-eye-slash' : 'fa-eye'}`}></i>
                                </button>
                                <button className="btn-icon-sm danger" title="Delete" onClick={() => handleDelete(t)}><i className="fas fa-times"></i></button>
                            </div>
                        </div>
                    </div>
                ))
            )}
        </div>
    );
};
