/* Main App + Router */

const App = () => {
  const initial = (window.location.hash || '#inicio').replace('#', '');
  const valid = ['inicio', 'servicios', 'nosotros', 'contacto'];
  const [route, setRoute] = React.useState(valid.includes(initial) ? initial : 'inicio');
  const [toast, setToast] = React.useState(null);

  const goto = (r) => {
    if (!valid.includes(r)) r = 'inicio';
    setRoute(r);
    window.location.hash = r;
    window.scrollTo({ top: 0, behavior: 'instant' });
  };

  React.useEffect(() => {
    const onHash = () => {
      const h = (window.location.hash || '#inicio').replace('#', '');
      if (valid.includes(h)) setRoute(h);
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, []);

  const showToast = (msg) => {
    setToast(msg);
    setTimeout(() => setToast(null), 4000);
  };

  return (
    <>
      <Navbar route={route} goto={goto} />

      <main>
        {route === 'inicio'    && <HomePage      goto={goto} />}
        {route === 'servicios' && <ServiciosPage goto={goto} />}
        {route === 'nosotros'  && <AboutPage     goto={goto} />}
        {route === 'contacto'  && <ContactPage   goto={goto} showToast={showToast} />}
      </main>

      <Footer goto={goto} />

      {/* Floating WhatsApp (hide on contact page) */}
      {route !== 'contacto' && (
        <a className="fab-wa" href="https://wa.me/56992278159" target="_blank" rel="noreferrer" aria-label="WhatsApp">
          <Icon name="whatsapp" size={26} />
        </a>
      )}

      {toast && (
        <div className="toast">
          <Icon name="check" size={18} stroke={2.5} />
          {toast}
        </div>
      )}
    </>
  );
};

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