I'm confused about the math for the delta-neutral portfolio.
Assume we have a short position in a European call option with price $p(t,S_t)$ and want to hedge it with the stock with price $S_t$. The portfolio value is $X(t,S_t)=-p(t,S_t)+\Delta\times S_t$. To make the portfolio delta neutral we require the portfolio to be insensitive to changes in $S_t$, thus, we have $\frac{\partial X}{\partial S}=-\frac{\partial p}{\partial S}+\Delta=0$ (assuming $\Delta$ does not depend on $S$). But somehow from here all textbooks give $\Delta=\frac{\partial p}{\partial S}$ which, in general, violates the assumption that $\Delta$ does not depend on $S$.
To see this more clearly, the portfolio $Y(t,S_t)=-p(t,S_t)+\underbrace{\frac{\partial p}{\partial S}}_{=\Delta}\times S_t$ is not delta neutral because $\frac{\partial Y}{\partial S}=-\frac{\partial p}{\partial S}+\frac{\partial^2 p}{\partial S^2}S+\frac{\partial p}{\partial S}\neq 0$ (unless it is gamma neutral). What is the mistake? What do I miss in the derivation?
Update: I was able to show that if one applies Ito's lemma to portfolio $Y$, then $dY_t = -\left(\frac{\partial p}{\partial t}+\frac{1}{2}\frac{\partial^2 p}{\partial S^2}\sigma^2 S_t^2 \right)dt$ which is independent of $dS_t$. But now my question is: where does the idea of gamma-hedging come from? Again, rigorous way of getting the fact that gamma is needed.