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

function AppInner() {
  const { path } = useRoute();

  let Page;
  if (path === '/' || path === '') Page = HomePage;
  else if (path.startsWith('/courses')) Page = CoursesPage;
  else if (path.startsWith('/universities')) Page = UniversitiesPage;
  else if (path.startsWith('/services')) Page = ServicesPage;
  else if (path.startsWith('/admission')) Page = AdmissionPage;
  else if (path.startsWith('/about')) Page = AboutPage;
  else if (path.startsWith('/contact')) Page = ContactPage;
  else Page = HomePage;

  return (
    <>
      <Nav />
      <main key={path} className="route-fade">
        <Page />
      </main>
      <Footer />
    </>
  );
}

function App() {
  const routeState = useRoute();
  const [tweaks, setTweaks] = useStateApp(() => ({ ...window.__TWEAKS }));

  useEffectApp(() => {
    const root = document.documentElement;
    root.style.setProperty('--accent', tweaks.accent);
    root.style.setProperty('--ink', tweaks.ink);

    const hex = tweaks.accent.replace('#','');
    const r = parseInt(hex.slice(0,2), 16);
    const g = parseInt(hex.slice(2,4), 16);
    const b = parseInt(hex.slice(4,6), 16);
    const lighten = (c, p) => Math.min(255, Math.round(c + (255 - c) * p));
    const darken = (c, p) => Math.max(0, Math.round(c * (1 - p)));
    const toHex = (v) => v.toString(16).padStart(2,'0');
    root.style.setProperty('--accent-soft', `#${toHex(lighten(r,0.2))}${toHex(lighten(g,0.2))}${toHex(lighten(b,0.2))}`);
    root.style.setProperty('--accent-deep', `#${toHex(darken(r,0.18))}${toHex(darken(g,0.18))}${toHex(darken(b,0.18))}`);

    const pads = { compact: 72, comfortable: 108, spacious: 144 };
    document.querySelectorAll('.section').forEach(s => {
      s.style.paddingTop = pads[tweaks.density] + 'px';
      s.style.paddingBottom = pads[tweaks.density] + 'px';
    });
  }, [tweaks]);

  return (
    <RouteContext.Provider value={routeState}>
      <AppInner />
      <Tweaks tweaks={tweaks} setTweaks={setTweaks} />
    </RouteContext.Provider>
  );
}

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