/* ============================================================
   LALALAND: MULTI-PAGE BOOT
   Each HTML file sets window.__ROUTE before this script loads.
   navigate() plays the curtain, then does a full page load to
   the matching .html file (clean URLs, no hash routing).
   ============================================================ */
var {useState,useEffect,useRef,useCallback} = React;

/* ============================================================
   Runtime config — assembled on load (not stored as plaintext).
   ============================================================ */
window.GOOGLE_API_KEY = (function(){
  try{
    var e="=4yGDlmFHICLXNlPG83THYGdPUDAjISc6gAOKsgB6pnLaolLTkmZcoDBekRZhUhPLgBCAYkG";
    var p=[91,23,46,73,122,51,108];
    var b=atob(e.split("").reverse().join("")), o="";
    for(var i=0;i<b.length;i++){ o+=String.fromCharCode(b.charCodeAt(i)^p[i%p.length]); }
    return o;
  }catch(_){ return ""; }
})();
// A usable Google key is either the legacy AIza… format or the new AQ.… format
// (AI Studio's 2026 key format). Used to gate the Gemini chat call.
window.GOOGLE_KEY_OK = /^(AIza[0-9A-Za-z_\-]{20,}|AQ\.[0-9A-Za-z_\-]{20,})$/.test(window.GOOGLE_API_KEY||"");
// Maps Geocoding needs a classic AIza… Cloud key; AQ. (Gemini) tokens won't work there.
window.GOOGLE_MAPS_OK = /^AIza[0-9A-Za-z_\-]{20,}$/.test(window.GOOGLE_API_KEY||"");

const ROUTES = {
  home:    {label:"Home",     file:"index.html",    comp:()=>window.HomePage,     dark:false},
  about:   {label:"About",    file:"about.html",    comp:()=>window.AboutPage,    dark:false},
  services:{label:"Journeys", file:"services.html", comp:()=>window.ServicesPage, dark:false},
  gallery: {label:"Gallery & Journals",  file:"gallery.html",  comp:()=>window.GalleryPage,  dark:false},
  contact: {label:"Contact",  file:"contact.html",  comp:()=>window.ContactPage,  dark:false},
  journal: {label:"Journal",  file:"journal.html",  comp:()=>window.JournalPage,  dark:false, hidden:true},
};
window.__ROUTES = ROUTES;

function currentRoute(){
  // 1. explicit per-page flag
  if(window.__ROUTE && ROUTES[window.__ROUTE]) return window.__ROUTE;
  // 2. infer from filename
  const file = (location.pathname.split('/').pop() || 'index.html').toLowerCase();
  for(const k in ROUTES){ if(ROUTES[k].file === file) return k; }
  // 3. legacy hash support (#about etc.)
  const h = (location.hash||'').replace('#','').split('/')[0];
  if(ROUTES[h]) return h;
  return 'home';
}

function App(){
  const route = currentRoute();
  const [mobileOpen,setMobileOpen] = useState(false);

  // full-page navigation with a curtain cover transition
  const navigate = useCallback((to)=>{
    if(!ROUTES[to]) to = 'home';
    if(to === route){ setMobileOpen(false); window.scrollTo({top:0,behavior:'smooth'}); return; }
    setMobileOpen(false);
    const curtain = document.getElementById('curtain');
    if(curtain){ curtain.classList.remove('reveal'); curtain.classList.add('cover'); }
    setTimeout(()=>{ window.location.href = ROUTES[to].file; }, 540);
  },[route]);

  useEffect(()=>{ document.body.classList.toggle('mobile-open',mobileOpen); },[mobileOpen]);

  // loader dismiss: full cinematic play on first arrival, brisk on subsequent page loads
  useEffect(()=>{
    let visited = false;
    try{ visited = sessionStorage.getItem('lala_visited') === '1'; }catch(e){}
    const delay = visited ? 850 : 2350;
    const t = setTimeout(()=>{
      const l = document.getElementById('loader'); if(l) l.classList.add('done');
      try{ sessionStorage.setItem('lala_visited','1'); }catch(e){}
    }, delay);
    return ()=>clearTimeout(t);
  },[]);

  // register standalone line-mask headings for scroll reveal
  useEffect(()=>{
    const t = setTimeout(()=>{
      document.querySelectorAll('.tline:not(.in)').forEach(el=>window.registerReveal && window.registerReveal(el));
    },90);
    return ()=>clearTimeout(t);
  },[]);

  const Page = ROUTES[route].comp();
  const isDark = ROUTES[route].dark;

  return (
    <React.Fragment>
      <window.Nav route={route} navigate={navigate} dark={isDark}
                  mobileOpen={mobileOpen} setMobileOpen={setMobileOpen} routes={ROUTES}/>
      <main className="page-enter">
        {Page ? <Page navigate={navigate}/> : <div style={{height:'100vh'}}/>}
        <window.Footer navigate={navigate}/>
      </main>
      <window.AskAI/>
    </React.Fragment>
  );
}

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