// Main app — hash router + page rendering

const VALID_ROUTES = ["home", "about", "services", "testimonials", "contact"];

function getRouteFromHash() {
  const h = (window.location.hash || "").replace(/^#/, "").trim();
  if (VALID_ROUTES.includes(h)) return h;
  return "home";
}

function App() {
  const [route, setRoute] = React.useState(getRouteFromHash());
  const apply = useApplyModal();

  React.useEffect(() => {
    const onHash = () => setRoute(getRouteFromHash());
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  const navigate = React.useCallback((to) => {
    window.location.hash = to;
    setRoute(to);
    // Smooth scroll to top on page nav
    window.scrollTo({ top: 0, behavior: "smooth" });
  }, []);

  const openApply = apply.openApply;

  let content = null;
  switch (route) {
    case "home":         content = <HomePage navigate={navigate} openApply={openApply} />; break;
    case "about":        content = <AboutPage navigate={navigate} openApply={openApply} />; break;
    case "services":     content = <ServicesPage navigate={navigate} openApply={openApply} />; break;
    case "contact":      content = <ContactPage navigate={navigate} openApply={openApply} />; break;
    case "testimonials": content = <TestimonialsPage navigate={navigate} openApply={openApply} />; break;
    default:             content = <HomePage navigate={navigate} openApply={openApply} />;
  }

  return (
    <div>
      <Nav route={route} navigate={navigate} />
      <React.Fragment key={route}>{content}</React.Fragment>
      <Footer navigate={navigate} />
      {apply.open && <ApplyModal serviceKey={apply.open} onClose={apply.close} />}
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
