// App router for the SCN2A Australia site prototype.
// Manages route, mobile menu, and tweak state (homepage direction, density, accent emphasis).

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
 "direction": "N",
 "density": "comfy",
 "accent": "balanced"
}/*EDITMODE-END*/;

// --- Real-path routing helpers --------------------------------------------
// The site is served at real URLs (/, /genetics, /ndis, ...). We derive the
// route from the pathname, with a legacy #hash fallback so previously shared
// links keep working. 'home' lives at '/'.
function pathForRoute(route) {
 return (!route || route === 'home') ? '/' : '/' + route;
}
function routeFromLocation() {
 if (typeof window === 'undefined') return 'home';
 let p = (window.location.pathname || '/').replace(/\.html$/, '').replace(/\/+$/, '');
 p = p.replace(/^\/+/, '');
 if (!p) {
 // At the root: honour a legacy #route hash if present.
 const h = (window.location.hash || '').replace('#', '');
 return h || 'home';
 }
 return p;
}

function App() {
 const [route, setRoute] = React.useState(() => routeFromLocation());
 const [mobileOpen, setMobileOpen] = React.useState(false);
 const [searchOpen, setSearchOpen] = React.useState(false);
 const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

 const navigate = React.useCallback((next) => {
 setRoute(next);
 window.scrollTo({ top: 0, behavior: 'instant' });
 if (typeof window !== 'undefined' && window.history && window.history.pushState) {
 window.history.pushState({ route: next }, '', pathForRoute(next));
 }
 }, []);

 // Re-derive the route on browser back/forward (real-path history) and on any
 // legacy #hash change, so old shared links still resolve.
 React.useEffect(() => {
 const onNav = () => {
 setRoute(routeFromLocation());
 window.scrollTo({ top: 0, behavior: 'instant' });
 };
 window.addEventListener('popstate', onNav);
 window.addEventListener('hashchange', onNav);
 return () => {
 window.removeEventListener('popstate', onNav);
 window.removeEventListener('hashchange', onNav);
 };
 }, []);

 // Refresh Lucide icons after every render
 React.useEffect(() => {
 if (window.lucide && window.lucide.createIcons) {
 window.lucide.createIcons();
 }
 });

 // Pick home variant from tweak
 const homes = { A: HomeA, B: HomeB, C: HomeC, N: HomeNeural };
 const HomeComponent = homes[t.direction] || HomeNeural;

 const pages = {
 'home': <HomeComponent navigate={navigate} />,
 'support': <SupportPage navigate={navigate} />,
 'change': <ChangePage navigate={navigate} />,
 'professionals': <ProfessionalsPage navigate={navigate} />,
 'involved': <InvolvedPage navigate={navigate} />,
 'walk': <WalkPage navigate={navigate} />,
 'walk-event': <WalkEventPage navigate={navigate} />,
 'about': <AboutPage navigate={navigate} />,
 'impact': <ImpactPage navigate={navigate} />,
 'partners': <PartnersPage navigate={navigate} />,
 'understand': <UnderstandLandingPage navigate={navigate} />,
 'what-is-dee': <WhatIsDEEPage navigate={navigate} />,
 'scn2a-disorders': <SCN2ADisordersPage navigate={navigate} />,
 'what-is-scn2a': <SCN2ADisordersPage navigate={navigate} />,
 'genetics': <GeneticsDiagnosisPage navigate={navigate} />,
 'seizures': <SeizuresPage navigate={navigate} />,
 'development': <DevelopmentPage navigate={navigate} />,
 'ndis': <NDISPage navigate={navigate} />,
 'carers': <CarerSupportPage navigate={navigate} />,
 'trials': <ClinicalTrialsPage navigate={navigate} />,
 'research': <ResearchOpportunitiesPage navigate={navigate} />,
 'publications': <PublicationsPage navigate={navigate} />,
 'global': <GlobalCollaborationPage navigate={navigate} />,
 'newly-diagnosed': <NewlyDiagnosedPage navigate={navigate} />,
 'families': <FamiliesPage navigate={navigate} />,
 'family-map': <FamilyMapPage navigate={navigate} />,
 'wills-story': <WillsStoryPage navigate={navigate} />,
 'navigator': <NavigatorPage navigate={navigate} />,
 'resources': <ResourcesPage navigate={navigate} />,
 'news': <NewsPage navigate={navigate} />,
 'epilepsy-inquiry': <EpilepsyInquiryPage navigate={navigate} />,
 'elsunersen-breakthrough': <ElsunersenBreakthroughPage navigate={navigate} />,
 'contact': <ContactPage navigate={navigate} />,
 'privacy': <PrivacyPage navigate={navigate} />,
 'accessibility': <AccessibilityPage navigate={navigate} />,
 'sparky': <SparkyStorybookPage navigate={navigate} />,
 };

 // Light header everywhere (we lead with warm/light, navy is an accent).
 // Only the legacy graphic direction C keeps a dark home header.
 const headerTheme = (route === 'home' && t.direction === 'C') ? 'dark' : 'light';

 // Prototype tweaks panel: only on localhost or with ?tweaks in the URL.
 // Hidden in production so it never ships to public visitors.
 const showTweaks = typeof window !== 'undefined' && (
 ['localhost', '127.0.0.1'].includes(window.location.hostname) ||
 window.location.search.includes('tweaks')
 );

 const containerClass = [
 `dir-${t.direction.toLowerCase()}`,
 t.density === 'compact' ? 'density-compact' : 'density-comfy',
 `accent-${t.accent}`,
 ].join(' ');

 return (
 <div className={containerClass}>
 <a href="#main-content" className="skip-link"
 onClick={(e) => { e.preventDefault(); const m = document.getElementById('main-content'); if (m) { m.focus(); m.scrollIntoView(); } }}>
 Skip to content
 </a>
 <Header route={route} navigate={navigate} onOpenMobile={() => setMobileOpen(true)} onOpenSearch={() => setSearchOpen(true)} theme={headerTheme} />
 <MobileMenu open={mobileOpen} onClose={() => setMobileOpen(false)} navigate={navigate} route={route} />
 <SearchOverlay open={searchOpen} onClose={() => setSearchOpen(false)} navigate={navigate} />
 <main id="main-content" tabIndex={-1} key={route + t.direction} data-screen-label={route}>
 {pages[route] || pages['home']}
 </main>
 <Footer navigate={navigate} />

 {showTweaks && (
 <TweaksPanel title="Tweaks">
 <TweakSection label="Homepage direction" />
 <DirectionPicker value={t.direction} onChange={(v) => setTweak('direction', v)} />
 <TweakSection label="Layout" />
 <TweakRadio label="Density" value={t.density} options={['compact', 'comfy']}
 onChange={(v) => setTweak('density', v)} />
 <TweakRadio label="Accent emphasis" value={t.accent} options={['teal', 'balanced', 'coral']}
 onChange={(v) => setTweak('accent', v)} />
 <TweakSection label="Jump to page" />
 <TweakSelect label="Navigate" value={route}
 options={[
 ['home', 'Home'],
 ['support', 'Support'],
 ['newly-diagnosed', 'Newly diagnosed'],
 ['families', 'What families need to know'],
 ['navigator', 'Navigation tool'],
 ['understand', 'Understand SCN2A & DEE'],
 ['what-is-dee', 'What is DEE?'],
 ['scn2a-disorders', 'SCN2A-related disorders'],
 ['genetics', 'Genetics & diagnosis'],
 ['seizures', 'Seizure types & management'],
 ['development', 'Developmental considerations'],
 ['ndis', 'NDIS Navigation Guide'],
 ['carers', 'Carer support & wellbeing'],
 ['change', 'Driving Change'],
 ['trials', 'Clinical trials'],
 ['research', 'Research opportunities'],
 ['professionals', 'Health Professionals'],
 ['involved', 'Get Involved'],
 ['walk', 'Walk Around Australia'],
 ['walk-event', 'SCN2A Walk Event (Sept)'],
 ['about', 'About'],
 ['impact', 'Our Impact'],
 ['partners', 'Partners'],
 ['publications', 'Publications'],
 ['global', 'Global Collaboration'],
 ['resources', 'Resources'],
 ['news', 'Blogs & news'],
 ['contact', 'Contact'],
 ]}
 onChange={(v) => navigate(v)} />
 </TweaksPanel>
 )}
 </div>
 );
}

// Custom large picker for the three homepage directions
function DirectionPicker({ value, onChange }) {
 const opts = [
 { id: 'N', label: 'N, Neural Ink (v2.0)', desc: 'Navy-anchored, warm-white canvas, strict mulberry.' },
 { id: 'A', label: 'A, Evidence Ledger', desc: 'Editorial type, monospace ledger, authority-first.' },
 { id: 'B', label: 'B, Hands & Voice', desc: 'Photo-led hero, family warmth into rigor.' },
 { id: 'C', label: 'C, The Network', desc: 'Graphic-led, dark teal, network motif.' },
 ];
 return (
 <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
 {opts.map(o => (
 <button key={o.id} onClick={() => onChange(o.id)}
 style={{
 textAlign: 'left', padding: '10px 12px',
 background: value === o.id ? 'rgba(13,27,42,0.12)' : 'rgba(255,255,255,0.55)',
 border: value === o.id ? '1px solid rgba(13,27,42,0.55)' : '0.5px solid rgba(0,0,0,0.1)',
 borderRadius: 0, cursor: 'pointer', fontFamily: 'inherit',
 color: '#29261b',
 display: 'flex', flexDirection: 'column', gap: 2,
 }}>
 <span style={{ fontWeight: 700, fontSize: 12 }}>{o.label}</span>
 <span style={{ fontSize: 11, color: 'rgba(41,38,27,0.6)' }}>{o.desc}</span>
 </button>
 ))}
 </div>
 );
}

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