Around the 17th century (1600s) an experienced seaman was rated as “midshipman” because of the location of his duty, or his compartment below deck — it was the middle of the ship or midship for short.
In the 18th century the title of midshipman transitioned to anyone who was a candidate for a commission on a ship.
From there the term midshipman came to mean an apprentice officer on a ship, someone who aspired for promotion.
That aspirational role seems to be where an old English term from the 17th century comes into play. An apprentice or servant was called a cocc (“one who strutted like a cock”)
The middle of the ship where an aspirational officer apprentice would roam like a proud chicken of the sea… thus probably generated the term “cockpit”.
The word “pit” likely referenced the midship again, where work was done or maybe also because the decks of a ship were lower versus high stern and bow.
The 1862 Man-o-War “Midshipman’s Diary: Cockpit Journal” makes this fairly plain to see.
Today midshipman is still a term used to describe the entry level role for someone who wants to become commissioned as a naval officer. However, now it means an academy on land instead of constrained into the middle of a ship at sea.
Cockpit meanwhile somehow elevated way beyond the aspiring midshipman into the place on a vessel for command and control, such as the nose of an airplane or aft area of a sailboat.
One other thought on this topic is that chickens had a superstitious meaning at sea. “Pig on the knee, safety at sea. A cock on the right, never lose a fight” was one saying about where to put sailor tattoos. Another was that the cock tattoo on a right foot would prevent drowning.
It’s hard to find evidence for why such superstitions evolved. Some say it was because wooden crates often floated ashore after a shipwreck with chickens surviving despite them being unable to fly or swim. Some might say chickens were a source of food to ensure human survival, meaning they represented good luck after a wreck.
In any case I doubt midships with crates of chickens is where cockpit comes from. Perky ostentatious midshipmen seems the more likely story, given British sea humor and the fact that a term like “pigpen” was never used.