All perfect praise be to Allah, The Lord of the Worlds. I testify that there is none worthy of worship except Allah, and that Muhammad is His slave and Messenger.
According to the majority of scholars, ejaculation due to thinking does not invalidate fasting; however, Imam Maalik is of the view that it does. Yet, the first view is what we adopt. In his Ikhtilaaf Al-A’emmah Al-ʿUlamaa’, Ibn Hubayrah said, “They (i.e. scholars) unanimously agree that whoever thinks lustfully of women and ejaculates, his fasting is still valid; however, Imam Maalik is of the opinion that the fasting of whoever does so is invalid, and thus should make up for it.”
So, keep away from such imaginations; do your best to do what protects your fasting from being invalidated; keep away from what might make you commit disobedience; beware of filling your records with sins and acts of disobedience, especially while you are still young; and accompany the righteous to benefit from them.
Allah knows best.