/* Torre Auro — App router and bootstrap */

class ErrorBoundary extends React.Component {
  constructor(p) { super(p); this.state = { err: null }; }
  static getDerivedStateFromError(err) { return { err }; }
  componentDidCatch(err, info) { console.error('Torre Auro error:', err, info); }
  render() {
    if (this.state.err) {
      return (
        <div style={{
          minHeight:'60vh', display:'flex', flexDirection:'column', alignItems:'center',
          justifyContent:'center', textAlign:'center', padding:'80px 24px', gap:18,
        }}>
          <div style={{ fontFamily:'var(--display)', fontSize:32, fontWeight:700, color:'var(--navy)', letterSpacing:'-.02em' }}>
            Algo no cargó bien.
          </div>
          <p style={{ color:'var(--muted)', maxWidth:380, lineHeight:1.6 }}>
            Recarga la página para continuar. Si el problema persiste, contáctanos al 229 302 7197.
          </p>
          <button className="btn btn-navy" onClick={() => { this.setState({ err:null }); window.location.href = '/'; }}>
            Volver al inicio
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}

function App() {
  const route = useRoute();

  // Resolve which page to render
  let page;
  let key = route;
  if (route === '/' || route === '') {
    page = <Home />;
    key = 'home';
  } else if (route === '/contacto') {
    page = <ContactPage />;
  } else if (route === '/perspectiva' || route === '/perspectiva/') {
    page = <PerspectivaIndex />;
    key = 'perspectiva';
  } else if (route.startsWith('/perspectiva/')) {
    const slug = route.replace(/^\/perspectiva\//, '').replace(/\/$/, '');
    const post = POST_BY_SLUG[slug];
    if (post) {
      page = <PerspectivaPost post={post} />;
      key = 'post-' + slug;
    } else {
      page = <PerspectivaIndex />;
      key = 'perspectiva';
      window.history.replaceState({}, '', '/perspectiva');
    }
  } else if (route === '/eventos' || route === '/eventos/') {
    page = <EventosIndex />;
    key = 'eventos';
  } else if (route.startsWith('/eventos/')) {
    const slug = route.replace(/^\/eventos\//, '').replace(/\/$/, '');
    const ev = EVENT_BY_SLUG[slug];
    if (ev) {
      page = <EventoDetail event={ev} />;
      key = 'event-' + slug;
    } else {
      page = <EventosIndex />;
      key = 'eventos';
      window.history.replaceState({}, '', '/eventos');
    }
  } else {
    // try match a floor by its route ID, or a floor/office detail
    const slug = route.replace(/^\/+/, '').replace(/\/$/, '');
    const parts = slug.split('/');
    const floor = FLOOR_BY_ID[parts[0]];
    if (floor && parts.length === 2) {
      const office = floor.offices.find(o => o.code === parts[1]);
      if (office) {
        page = <OfficeDetail floor={floor} office={office} />;
        key = 'office-' + parts[0] + '-' + parts[1];
      } else {
        page = <LevelPage floor={floor} />;
        window.history.replaceState({}, '', floor.route);
      }
    } else if (floor) {
      page = <LevelPage floor={floor} />;
    } else {
      // 404 — redirect to home
      page = <Home />;
      if (typeof window !== 'undefined') {
        window.history.replaceState({}, '', '/');
      }
      key = 'home';
    }
  }

  // Update document title
  useEffect(() => {
    const t = (() => {
      if (route === '/') return 'Torre Auro · El ecosistema empresarial de Boca del Río';
      if (route === '/contacto') return 'Contacto · Torre Auro';
      if (route === '/perspectiva') return 'Perspectiva · Torre Auro';
      if (route.startsWith('/perspectiva/')) {
        const s = route.replace(/^\/perspectiva\//, '').replace(/\/$/, '');
        const p = POST_BY_SLUG[s];
        return p ? `${p.title} · Perspectiva` : 'Perspectiva · Torre Auro';
      }
      if (route === '/eventos') return 'El Calendario · Torre Auro';
      if (route.startsWith('/eventos/')) {
        const s = route.replace(/^\/eventos\//, '').replace(/\/$/, '');
        const ev = EVENT_BY_SLUG[s];
        return ev ? `${ev.title} · Torre Auro` : 'El Calendario · Torre Auro';
      }
      const slug = route.replace(/^\/+/, '').replace(/\/$/, '');
      const parts = slug.split('/');
      const f = FLOOR_BY_ID[parts[0]];
      if (f && parts.length === 2) return `${parts[1]} · ${f.sh} · Torre Auro`;
      if (f) return `${f.sh} · ${f.short} · Torre Auro`;
      return 'Torre Auro';
    })();
    document.title = t;
  }, [route]);

  return (
    <div className="app-root">
      <Nav route={route} />
      <ErrorBoundary key={key}>
        <main key={key}>
          {page}
        </main>
      </ErrorBoundary>
      <Footer />
      <ChatWidget />
      <ProjectModal />
    </div>
  );
}

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