(function() {
  const { useState, useEffect } = React;

  function parseHash(hash) {
    const h = (hash || '').replace(/^#\/?/, '');
    if (!h || h === '/') return { page: 'home' };
    const parts = h.split('/').filter(Boolean);
    if (parts[0] === 'property' && parts[1] && parts[2] === 'unit' && parts[3]) {
      return { page: 'unit', propertySlug: parts[1], unitSlug: parts[3] };
    }
    if (parts[0] === 'property' && parts[1]) {
      return { page: 'property', propertySlug: parts[1] };
    }
    if (parts[0] === 'contact') return { page: 'contact' };
    return { page: 'home' };
  }

  function App() {
    const [route, setRoute] = useState(() => parseHash(window.location.hash));

    useEffect(() => {
      const onHash = () => {
        setRoute(parseHash(window.location.hash));
        window.scrollTo(0, 0);
      };
      window.addEventListener('hashchange', onHash);
      return () => window.removeEventListener('hashchange', onHash);
    }, []);

    let content;
    switch (route.page) {
      case 'property':
        content = <PropertyPage propertySlug={route.propertySlug} />;
        break;
      case 'unit':
        content = <UnitPage propertySlug={route.propertySlug} unitSlug={route.unitSlug} />;
        break;
      case 'contact':
        content = <ContactPage />;
        break;
      default:
        content = <HomePage />;
    }

    return (
      <div className="site-wrapper">
        <Header />
        <main className="site-content">
          {content}
        </main>
        <Footer />
      </div>
    );
  }

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