Syllable codas in Old/Middle French, plus analogy.
In the development of French, Latin /e/
developed differently in open syllables vs closed syllables: this is why we have "detain" (MFr dé.te.nir) vs "detention" (MFr dé.ten.tion).
The form in "detain" was usually spelled ei or ey in Middle English, separate from the vowel spelled ai or ay (which, in French, developed from Latin /a/
in open syllables). The two were probably something like [ej aj]
respectively, though of course we can't be too certain about pronunciation.
But over the lifetime of Middle English, those two diphthongs merged together, and their spellings varied wildly as people were no longer sure which ones to spell with an e and which ones to spell with an a. Eventually, "detain" and its brethren ended up spelled with ai, even though that vowel comes from a Latin e instead of a Latin a.
(Forms like "entertainment", with ai in a closed syllable, were either formed within English, or their spellings were changed by analogy with "entertain" and "entertaining".)