package handlers

import (
	"net/http"
	"os"
	"strings"
)

// handleNotFoundPage is the catch-all for authenticated paths that match no
// other route. It serves the chromed dist/notfound.html shell with HTTP 404
// so users hitting a typo or stale URL see the sidebar + a friendly card
// instead of the bare default `404 page not found`. Anonymous visitors are
// redirected to /login by the auth middleware before reaching this handler,
// so it only ever runs for logged-in users.
//
// API paths (`/api/*`) return JSON 404 instead — XHR callers don't want HTML.
func handleNotFoundPage(w http.ResponseWriter, r *http.Request) {
	if strings.HasPrefix(r.URL.Path, "/api/") {
		writeJSON(w, http.StatusNotFound, map[string]string{"error": "not found"})
		return
	}
	body, err := os.ReadFile("dist/notfound.html")
	if err != nil {
		http.Error(w, "404 page not found", http.StatusNotFound)
		return
	}
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	w.WriteHeader(http.StatusNotFound)
	_, _ = w.Write(body)
}
