// app.jsx — main app with router and tweaks

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "dark",
  "typePair": "fraunces",
  "gold": "#C6A96B",
  "heroVariant": "parallax",
  "heroImage": "images/samples/image14.webp",
  "experienceLayout": "mosaic"
}/*EDITMODE-END*/;

const HERO_IMAGES = [
  { id: 'island',   label: 'Island',   url: "https://images.unsplash.com/photo-1586611292717-f828b167408c?auto=format&fit=crop&w=2400&q=80" },
  { id: 'tea',      label: 'Tea',      url: "https://images.unsplash.com/photo-1561365452-adb940139ffa?auto=format&fit=crop&w=2400&q=80" },
  { id: 'coast',    label: 'Coast',    url: "https://images.unsplash.com/photo-1571896349842-33c89424de2d?auto=format&fit=crop&w=2400&q=80" },
  { id: 'wildlife', label: 'Wildlife', url: "https://images.unsplash.com/photo-1581852017103-68ac65514cf7?auto=format&fit=crop&w=2400&q=80" },
];

const GOLD_OPTIONS = ['#C6A96B', '#B89455', '#D4B574', '#A38447'];

const TYPE_OPTIONS = [
  { id: 'fraunces', label: 'Fraunces' },
  { id: 'cormorant', label: 'Cormorant' },
  { id: 'italiana', label: 'Italiana' },
  { id: 'playfair', label: 'Playfair' },
];

// Converts a URL pathname to internal route + IDs.
// Unknown paths fall back to home.
function parsePathname(pathname) {
  const parts = pathname.split('/').filter(Boolean);
  if (parts.length === 0)                          return { route: 'home',    tourId: null,     articleId: null };
  if (parts[0] === 'tours'   && parts[1])          return { route: 'detail',  tourId: parts[1], articleId: null };
  if (parts[0] === 'tours')                        return { route: 'tours',   tourId: null,     articleId: null };
  if (parts[0] === 'journal' && parts[1])          return { route: 'article', tourId: null,     articleId: parts[1] };
  if (parts[0] === 'journal')                      return { route: 'journal', tourId: null,     articleId: null };
  if (parts[0] === 'about')                        return { route: 'about',   tourId: null,     articleId: null };
  if (parts[0] === 'contact')                      return { route: 'contact', tourId: null,     articleId: null };
  if (parts[0] === 'privacy')                      return { route: 'privacy', tourId: null,     articleId: null };
  if (parts[0] === 'terms')                        return { route: 'terms',   tourId: null,     articleId: null };
  if (parts[0] === 'cookies')                      return { route: 'cookies', tourId: null,     articleId: null };
  return { route: 'home', tourId: null, articleId: null };
}

// Converts internal route + IDs to a URL pathname.
function routeToPath(r, tourId, articleId) {
  if (r === 'detail'  && tourId)    return '/tours/'   + tourId;
  if (r === 'detail')               return '/tours';
  if (r === 'tours')                return '/tours';
  if (r === 'article' && articleId) return '/journal/' + articleId;
  if (r === 'article')              return '/journal';
  if (r === 'journal')              return '/journal';
  if (r === 'about')                return '/about';
  if (r === 'contact')              return '/contact';
  if (r === 'privacy')              return '/privacy';
  if (r === 'terms')                return '/terms';
  if (r === 'cookies')              return '/cookies';
  return '/';
}

const App = () => {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [route, setRoute] = React.useState(() => parsePathname(window.location.pathname).route);
  const [activeTourId, setActiveTourId] = React.useState(() => parsePathname(window.location.pathname).tourId || 'highlands');
  const [activeArticleId, setActiveArticleId] = React.useState(() => parsePathname(window.location.pathname).articleId || 'wildlife-safari-sri-lanka');

  // Central navigation — updates React state AND browser history.
  const navigate = React.useCallback((r, id) => {
    const tid = r === 'detail'  ? (id || 'highlands')                  : null;
    const aid = r === 'article' ? (id || 'wildlife-safari-sri-lanka')  : null;
    if (tid) setActiveTourId(tid);
    if (aid) setActiveArticleId(aid);
    setRoute(r);
    window.scrollTo({ top: 0, behavior: 'instant' });
    history.pushState({}, '', routeToPath(r, tid, aid));
  }, []);

  // Handle browser back / forward buttons.
  React.useEffect(() => {
    const onPop = () => {
      const s = parsePathname(window.location.pathname);
      if (s.tourId)    setActiveTourId(s.tourId);
      if (s.articleId) setActiveArticleId(s.articleId);
      setRoute(s.route);
      window.scrollTo({ top: 0, behavior: 'instant' });
    };
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, []);

  // Expose nav globally so non-React callbacks can route.
  React.useEffect(() => {
    window.__nav = navigate;
  }, [navigate]);

  // Apply theme + type to <html>
  React.useEffect(() => {
    document.documentElement.setAttribute('data-theme', t.theme);
    document.documentElement.setAttribute('data-type', t.typePair);
    document.documentElement.style.setProperty('--gold', t.gold);
    // Recompute gold-2 by darkening
    document.documentElement.style.setProperty('--gold-2', t.gold);
  }, [t.theme, t.typePair, t.gold]);

  let page = null;
  if (route === 'home') page = <HomePage tweaks={t} />;
  else if (route === 'tours') page = <ToursPage />;
  else if (route === 'detail') page = <DetailPage tourId={activeTourId} />;
  else if (route === 'journal') page = <JournalPage />;
  else if (route === 'article') page = <ArticlePage articleId={activeArticleId} />;
  else if (route === 'about') page = <AboutPage />;
  else if (route === 'contact') page = <ContactPage />;
  else if (route === 'privacy') page = <PrivacyPage />;
  else if (route === 'terms') page = <TermsPage />;
  else if (route === 'cookies') page = <CookiesPage />;

  return (
    <>
      <Nav route={route} setRoute={navigate} />
      <main key={route}>
        {page}
      </main>
      {route !== 'contact' && <Footer setRoute={navigate} />}

      <TweaksPanel title="Tweaks">
        <TweakSection label="Theme" />
        <TweakRadio
          label="Mode"
          value={t.theme}
          options={['dark', 'light']}
          onChange={v => setTweak('theme', v)}
        />
        <TweakColor
          label="Gold accent"
          value={t.gold}
          options={GOLD_OPTIONS}
          onChange={v => setTweak('gold', v)}
        />

        <TweakSection label="Typography" />
        <TweakSelect
          label="Display serif"
          value={t.typePair}
          options={TYPE_OPTIONS.map(o => ({ value: o.id, label: o.label }))}
          onChange={v => setTweak('typePair', v)}
        />

        <TweakSection label="Hero" />
        <TweakRadio
          label="Treatment"
          value={t.heroVariant}
          options={['parallax', 'still', 'split']}
          onChange={v => setTweak('heroVariant', v)}
        />
        <TweakSelect
          label="Hero image"
          value={t.heroImage}
          options={HERO_IMAGES.map(h => ({ value: h.url, label: h.label }))}
          onChange={v => setTweak('heroImage', v)}
        />

        <TweakSection label="Experiences" />
        <TweakRadio
          label="Layout"
          value={t.experienceLayout}
          options={['mosaic', 'grid', 'two-up']}
          onChange={v => setTweak('experienceLayout', v)}
        />

        <TweakSection label="Navigate" />
        <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:6, marginTop: 4}}>
          {['home','tours','detail','journal','article','about','contact'].map(r => (
            <TweakButton key={r} onClick={() => navigate(r)}>
              {r === 'detail' ? 'tour detail' : r === 'article' ? 'article' : r}
            </TweakButton>
          ))}
        </div>
      </TweaksPanel>
    </>
  );
};

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