// app.jsx — router + state + tweaks
// Set to true ONLY during design review. Production deploy should keep this false
// so the floating Tweaks panel is hidden from end users.
const SHOW_TWEAKS = false;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "direction": "A",
  "locale": "en",
  "dark": false
}/*EDITMODE-END*/;

// Full SEO locale list (80) for URL detection; UI locale picker still uses LOCALES.
const LOCALE_CODES = (typeof LOCALE_CODES_ALL !== 'undefined' && LOCALE_CODES_ALL.length)
  ? LOCALE_CODES_ALL
  : ['en','id','ja','ko','it','fr','de','es'];

// Initial locale = window.__INITIAL_LOCALE (injected by Worker) OR first path segment OR 'en'.
function initialLocale() {
  if (typeof window.__INITIAL_LOCALE === 'string' && LOCALE_CODES.includes(window.__INITIAL_LOCALE)) {
    return window.__INITIAL_LOCALE;
  }
  const seg = (location.pathname.split('/').filter(Boolean)[0] || '').toLowerCase();
  return LOCALE_CODES.includes(seg) ? seg : 'en';
}

// Parse hash routes. Supports:
//   /              → { locale: default, path: '/' }
//   /<locale>/...  → { locale, path: '/...' }
//   /<anything>    → { locale: default, path: '/anything' }
function parseHash(defaultLocale = 'en') {
  const h = (location.hash || '').replace(/^#/, '') || '/';
  const parts = h.split('/').filter(Boolean);
  if (parts.length === 0) return { locale: defaultLocale, path: '/' };
  if (LOCALE_CODES.includes(parts[0])) {
    const rest = '/' + parts.slice(1).join('/');
    return { locale: parts[0], path: rest === '/' ? '/' : rest };
  }
  return { locale: defaultLocale, path: '/' + parts.join('/') };
}

function App() {
  const startLocale = initialLocale();
  const [tweaks, setTweak] = useTweaks({ ...TWEAK_DEFAULTS, locale: startLocale });
  const [route, setRoute] = useState(() => parseHash(startLocale));
  const [localePickerOpen, setLocalePickerOpen] = useState(false);
  const [cookMode, setCookMode] = useState(false);

  // sync route from hash
  useEffect(() => {
    const onHash = () => {
      const r = parseHash(tweaks.locale);
      setRoute(r);
      if (r.locale !== tweaks.locale && LOCALE_CODES.includes(r.locale)) {
        setTweak('locale', r.locale);
      }
      window.scrollTo(0, 0);
    };
    window.addEventListener('hashchange', onHash);
    return () => window.removeEventListener('hashchange', onHash);
  }, [tweaks.locale, setTweak]);

  // apply data-direction and data-theme to <html>
  // Direction is locked to "A" (Warm) for production; ignore tweaks.direction unless
  // SHOW_TWEAKS is enabled for design review.
  useEffect(() => {
    const root = document.documentElement;
    root.setAttribute('data-direction', SHOW_TWEAKS ? tweaks.direction : 'A');
    if (!cookMode) root.setAttribute('data-theme', tweaks.dark ? 'dark' : 'light');
  }, [tweaks.direction, tweaks.dark, cookMode]);

  // navigate(): writes new hash. Auto-locales recipe links; everything else stays unprefixed.
  const navigate = (newPath) => {
    location.hash = newPath;
  };

  const locale = tweaks.locale || 'en';
  const path = route.path;

  // route resolution
  let screen;
  if (cookMode) {
    screen = <CookMode locale={locale} onExit={()=>setCookMode(false)} />;
  } else if (path.startsWith('/r/')) {
    screen = <RecipeScreen locale={route.locale} onNavigate={navigate} onCookMode={()=>setCookMode(true)} />;
  } else if (path === '/ask' || path === '/search') {
    screen = <AIAnswerScreen locale={locale} onNavigate={navigate} />;
  } else if (CATEGORIES[path]) {
    screen = <CategoryScreen slug={path} locale={locale} onNavigate={navigate} />;
  } else if (['/about','/how-we-test','/editors','/careers','/press','/accessibility','/contact','/privacy','/terms'].includes(path)) {
    screen = <InfoScreen slug={path} onNavigate={navigate} />;
  } else if (path === '/') {
    screen = <HomeScreen locale={locale} onNavigate={navigate} />;
  } else {
    screen = <InfoScreen slug={path} onNavigate={navigate} />;
  }

  return (
    <>
      {!cookMode && (
        <Header
          locale={locale}
          route={path}
          onNavigate={navigate}
          onOpenLocale={()=>setLocalePickerOpen(true)}
        />
      )}

      <main key={path + locale}>
        {screen}
      </main>

      {!cookMode && <Footer locale={locale} onNavigate={navigate} />}

      <LocalePicker
        open={localePickerOpen}
        onClose={()=>setLocalePickerOpen(false)}
        locale={locale}
        onPick={(code) => {
          // Full navigation to /<code>/ so Worker serves the locale-canonical HTML
          // (sets <html lang>, canonical, og:url, window.__INITIAL_LOCALE).
          const onRecipe = path.startsWith('/r/');
          const target = onRecipe ? `/${code}/#/r/${RECIPE.slug}` : `/${code}/`;
          location.href = target;
        }}
      />

      {/* Tweaks panel hidden in production build. Toggle SHOW_TWEAKS to re-enable for design review. */}
      {SHOW_TWEAKS && (
        <TweaksPanel title="Tweaks">
          <TweakSection label="Direction" />
          <TweakRadio label="Theme"
            value={tweaks.direction}
            options={[
              { value: 'A', label: 'Warm' },
              { value: 'B', label: 'Bold' },
              { value: 'C', label: 'Scandi' },
            ]}
            onChange={v=>setTweak('direction', v)} />
          <DirectionPreview value={tweaks.direction} />

          <TweakSection label="Display" />
          <TweakToggle label="Dark mode" value={tweaks.dark}
            onChange={v=>setTweak('dark', v)} />

          <TweakSection label="Locale" />
          <LocaleGrid current={locale} onPick={v=>setTweak('locale', v)} />

          <TweakSection label="Navigation" />
          <TweakButton label="🌍 World homepage" onClick={()=>navigate(`/${locale}/`)} />
          <TweakButton label="🍪 Recipe page" onClick={()=>navigate(`/${locale}/r/${RECIPE.slug}`)} />
          <TweakButton label="▶ Cook mode" onClick={()=>{ navigate(`/${locale}/r/${RECIPE.slug}`); setTimeout(()=>setCookMode(true), 60); }} />
          <TweakButton label="✨ AI Sous-Chef" onClick={()=>navigate(`/${locale}/ask`)} />
        </TweaksPanel>
      )}
    </>
  );
}

// Visual preview for each direction inside the panel
const DirectionPreview = ({ value }) => {
  const dirs = {
    A: { name: 'Warm Editorial', bg: '#faf6ef', ink: '#1f160e', accent: '#b8451f', font: '"Lora", serif' },
    B: { name: 'Contemporary',   bg: '#ffffff', ink: '#0a0a0a', accent: '#ff3b1f', font: '"Space Grotesk", sans-serif' },
    C: { name: 'Scandinavian',   bg: '#f5f2ed', ink: '#2a2520', accent: '#6b7a5a', font: '"Cormorant Garamond", serif' },
  };
  const d = dirs[value] || dirs.A;
  return (
    <div style={{
      background: d.bg, color: d.ink,
      padding: '10px 12px', borderRadius: 8,
      border: '1px solid rgba(0,0,0,.06)', marginTop: 2,
      display: 'flex', alignItems: 'center', gap: 10,
    }}>
      <div style={{
        width: 28, height: 28, borderRadius: 999, background: d.accent,
        color: '#fff', display: 'grid', placeItems: 'center',
        fontFamily: d.font, fontSize: 14, fontWeight: 600,
      }}>i</div>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontFamily: d.font, fontSize: 14, fontWeight: 500, lineHeight: 1.1 }}>{d.name}</div>
        <div style={{ fontSize: 10, opacity: .6, marginTop: 2 }}>{d.font.split(',')[0].replace(/"/g,'')}</div>
      </div>
    </div>
  );
};

const LocaleGrid = ({ current, onPick }) => (
  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 4 }}>
    {LOCALES.map(l => (
      <button key={l.code} onClick={()=>onPick(l.code)}
        title={l.name}
        style={{
          padding: '8px 4px', borderRadius: 6,
          background: current === l.code ? '#29261b' : 'transparent',
          color: current === l.code ? '#fff' : 'inherit',
          border: '1px solid rgba(0,0,0,.08)',
          fontFamily: 'ui-monospace, "SFMono-Regular", monospace',
          fontSize: 10, fontWeight: 600, letterSpacing: '.05em',
          cursor: 'pointer', textTransform: 'uppercase',
          transition: 'all .12s ease',
        }}>
        {l.flag}
      </button>
    ))}
  </div>
);

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