const { useEffect, useState } = React;

function normalizePath(pathname) {
  if (!pathname || pathname === "/" || pathname === "/index.html") {
    return "/";
  }

  if (pathname.length > 1 && pathname.endsWith("/")) {
    return pathname;
  }

  if (pathname.indexOf(".") === -1) {
    return pathname + "/";
  }

  return pathname;
}

function App() {
  const [scrolled, setScrolled] = useState(false);

  useEffect(function bindScrollListener() {
    const onScroll = function onScroll() {
      setScrolled(window.scrollY > 20);
    };

    onScroll();
    window.addEventListener("scroll", onScroll);
    return function cleanup() {
      window.removeEventListener("scroll", onScroll);
    };
  }, []);

  const currentPath = normalizePath(window.location.pathname);
  const links = [
    { label: "Inicio", href: "/" },
    { label: "Sobre Nosotros", href: "/sobre-nosotros/" },
    { label: "Especialidades", href: "/especialidades/" },
    { label: "Contacto", href: "/contacto/" },
  ];

  const pageMap = {
    "/": {
      title: "Hernández & Asociados",
      render: function renderHome() {
        return <window.PageViews.HomePage />;
      },
    },
    "/sobre-nosotros/": {
      title: "Sobre Nosotros | Hernández & Asociados",
      render: function renderAbout() {
        return <window.PageViews.AboutPage />;
      },
    },
    "/especialidades/": {
      title: "Especialidades | Hernández & Asociados",
      render: function renderSpecialties() {
        return <window.PageViews.SpecialtiesPage />;
      },
    },
    "/contacto/": {
      title: "Contacto | Hernández & Asociados",
      render: function renderContact() {
        return <window.PageViews.ContactPage />;
      },
    },
  };

  const activePage = pageMap[currentPath] || pageMap["/"];

  useEffect(
    function syncDocumentTitle() {
      document.title = activePage.title;
    },
    [activePage]
  );

  return (
    <div className="page-shell">
      <window.NavBar links={links} scrolled={scrolled} currentPath={currentPath} />
      <main>{activePage.render()}</main>
      <window.WhatsAppButton />
      <window.SiteFooter links={links} currentPath={currentPath} />
    </div>
  );
}

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