// Main app — router + language state

const { useState: useStateApp, useEffect: useEffectApp } = React;

function App() {
  // route: { page, slug?, area? }
  const [route, setRoute] = useStateApp({ page: "home" });
  const [lang, setLang] = useStateApp("en");
  const t = I18N[lang];

  // Normalise navigate input
  const navigate = (next) => {
    if (typeof next === "string") setRoute({ page: next });
    else setRoute(next);
    window.scrollTo({ top: 0, behavior: "instant" });
  };

  useEffectApp(() => {
    document.documentElement.lang = lang === "en" ? "en" : lang === "ar" ? "ar" : "ru";
    document.documentElement.dir = I18N[lang].dir;
  }, [lang]);

  // Top-level layout switching by route.page
  let body;
  // Determine "active" page id for nav highlight
  const navPage =
    route.page === "practice-detail" ? "practice" :
    route.page === "insight-detail" ? "insights" :
    route.page;

  switch (route.page) {
    case "home":
      body = <HomePage t={t} navigate={navigate} />;
      break;
    case "practice":
      body = <PracticeListPage navigate={navigate} />;
      break;
    case "practice-detail":
      body = <PracticeDetailPage slug={route.slug} navigate={navigate} t={t} />;
      break;
    case "firm":
      body = <FirmPage navigate={navigate} />;
      break;
    case "insights":
      body = <InsightsPage navigate={navigate} />;
      break;
    case "insight-detail":
      body = <InsightDetailPage slug={route.slug} navigate={navigate} />;
      break;
    case "contact":
      body = <ContactPage navigate={navigate} t={t} prefillArea={route.area} />;
      break;
    default:
      body = <HomePage t={t} navigate={navigate} />;
  }

  return (
    <React.Fragment>
      <Header route={{ page: navPage }} navigate={navigate} lang={lang} setLang={setLang} t={t} />
      <div key={route.page + (route.slug || "")} style={{ animation: "fadeIn 320ms ease" }}>
        {body}
      </div>
      <Footer t={t} navigate={navigate} setLang={setLang} lang={lang} />
      <style>{`
        @keyframes fadeIn { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: translateY(0); } }
      `}</style>
    </React.Fragment>
  );
}

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