// ui_kits/website/App.jsx — composes the homepage and wires interactions.
//
// Owns the language state, the current view (home / section / post), and the
// active section. Sharable via LangContext for nested string lookups.

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "pairing": "wellness",
  "sectionHero": "colorful",
  "sectionFeatured": "split"
}/*EDITMODE-END*/;

const PAIRING_DEFS = {
  current: {
    label: 'Legacy — Droid Serif + Arial',
    blurb: 'The old Wix default — Arial body with a Droid Serif accent. Kept here for comparison only; the system has moved on.',
    serif: '"Droid Serif", Georgia, serif',
    sans:  'Arial, "Arimo", Helvetica, sans-serif',
  },
  magazine: {
    label: 'Magazine — Bodoni Moda + Newsreader',
    blurb: 'Serif-on-serif. High-contrast didone display echoes the logo; warm humanist serif for body. Most editorial.',
    serif: '"Bodoni Moda", "Didot", "Bodoni 72", serif',
    sans:  '"Newsreader", "Source Serif Pro", Georgia, serif',
  },
  modern: {
    label: 'Modern — DM Serif Display + Inter',
    blurb: 'Display serif + clean modern grotesque. Confident, contemporary, very web-native.',
    serif: '"DM Serif Display", "Playfair Display", Georgia, serif',
    sans:  '"Inter", -apple-system, "Segoe UI", sans-serif',
  },
  wellness: {
    label: 'Wellness — Playfair Display + Lora',
    blurb: 'The Goop / Apartment Therapy register. Romantic display serif, warm transitional body serif.',
    serif: '"Playfair Display", Georgia, serif',
    sans:  '"Lora", Georgia, serif',
  },
};

function applyPairing(key) {
  const p = PAIRING_DEFS[key] || PAIRING_DEFS.current;
  document.documentElement.style.setProperty('--font-serif', p.serif);
  document.documentElement.style.setProperty('--font-sans',  p.sans);
}

// Article categories that have full section pages.
const ARTICLE_SECTIONS = new Set(['Health', 'Beauty', 'Nutrition', 'Exercise']);

function App() {
  const [tweak, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [lang, setLang] = useLang();
  const [view, setView] = React.useState('home');           // 'home' | 'section' | 'post' | 'podcast'
  const [activeNav, setActiveNav] = React.useState('Health');
  const [openPost, setOpenPost] = React.useState(null);     // selected post object (already resolved)

  React.useEffect(() => { applyPairing(tweak.pairing); }, [tweak.pairing]);

  // Scroll to top on view change so the user lands at the section / post hero.
  React.useEffect(() => {
    window.scrollTo({ top: 0, behavior: 'instant' in window ? 'instant' : 'auto' });
  }, [view, activeNav, openPost && openPost.id]);

  // Listen for nav events fired by descendants (breadcrumbs, related cards).
  React.useEffect(() => {
    const onNav = (e) => {
      const d = e.detail || {};
      if (d.view === 'home') {
        setView('home');
      } else if (d.view === 'section' && d.section) {
        setActiveNav(d.section);
        setOpenPost(null);
        setView('section');
      } else if (d.view === 'podcast') {
        setActiveNav('Podcasts');
        setOpenPost(null);
        setView('podcast');
      }
    };
    window.addEventListener('app:navigate', onNav);
    return () => window.removeEventListener('app:navigate', onNav);
  }, []);

  // Open an article = switch view to 'post' and stash the resolved post.
  const openPostPage = React.useCallback((post) => {
    if (!post) return;
    // The post objects coming out of BlogGrid / SectionPage are already
    // resolved (see resolvePost in BlogGrid.jsx). The Hero "Read this week"
    // path used to pass a raw bilingual post, so resolve defensively.
    const resolved = (post.title && typeof post.title === 'object')
      ? resolvePost(post, lang)
      : post;
    setOpenPost(resolved);
    setView('post');
  }, [lang]);

  // When the user switches languages mid-article, re-resolve the open post
  // so its title / excerpt / date update too.
  const openPostId = openPost && openPost.id;
  React.useEffect(() => {
    if (!openPostId) return;
    const raw = (window.SAMPLE_POSTS || []).find(p => p.id === openPostId);
    if (raw) setOpenPost(resolvePost(raw, lang));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [lang]);

  const closePostPage = () => {
    // Return to whichever view the user came from. If the post is in an
    // article section, drop them on that section page; otherwise home.
    if (openPost && ARTICLE_SECTIONS.has(openPost.category)) {
      setActiveNav(openPost.category);
      setView('section');
    } else {
      setView('home');
    }
    setOpenPost(null);
  };

  // Header / strip nav.
  const handleNav = (key) => {
    setActiveNav(key);
    setOpenPost(null);
    if (ARTICLE_SECTIONS.has(key)) {
      setView('section');
    } else if (key === 'Podcasts') {
      setView('podcast');
    } else {
      setView('home');
    }
  };

  const goHome = () => { setView('home'); setActiveNav('Health'); setOpenPost(null); };

  const def = PAIRING_DEFS[tweak.pairing] || PAIRING_DEFS.current;

  return (
    <LangContext.Provider value={lang}>
      <div className="page">
        <Header
          active={activeNav}
          lang={lang}
          onNav={handleNav}
          onLogoClick={goHome}
          onSetLang={setLang}
        />

        {view === 'home' && (
          <React.Fragment>
            <Hero
              onPrimary={() => openPostPage(SAMPLE_POSTS[0])}
              onSecondary={() => { setActiveNav('Podcasts'); setView('podcast'); }}
            />
            <CategoryStrip lang={lang} onPick={handleNav}/>
            <BlogGrid onOpenPost={openPostPage}/>
            <HomeVideoBlock/>
            <div id="podcast"><PodcastSection/></div>
            <ShopSection/>
            <AboutFounder/>
            <Newsletter/>
          </React.Fragment>
        )}

        {view === 'podcast' && (
          <PodcastPage/>
        )}

        {view === 'section' && (
          <SectionPage
            section={activeNav}
            onOpenPost={openPostPage}
            heroVariant={tweak.sectionHero}
            featuredVariant={tweak.sectionFeatured}
          />
        )}

        {view === 'post' && openPost && (
          <PostPage
            post={openPost}
            onClose={closePostPage}
            onOpenPost={openPostPage}
          />
        )}

        <Footer/>

        <TweaksPanel title="Design tweaks">
          <TweakSection label="Typography pairing">
            <TweakSelect
              label="Pairing"
              value={tweak.pairing}
              options={Object.entries(PAIRING_DEFS).map(([value, def]) => ({ value, label: def.label }))}
              onChange={(v) => setTweak('pairing', v)}
            />
          </TweakSection>

          <div style={{
            padding: '10px 14px', margin: '6px 0 4px',
            background: 'rgba(0,0,0,0.04)', borderRadius: 8,
            fontFamily: 'system-ui, sans-serif', fontSize: 11.5, lineHeight: 1.5,
            color: '#525150',
          }}>{def.blurb}</div>

          <TweakSection label="Section page — hero">
            <TweakRadio
              value={tweak.sectionHero}
              onChange={(v) => setTweak('sectionHero', v)}
              options={[
                { value: 'minimal',  label: 'Minimal' },
                { value: 'colorful', label: 'Colorful' },
                { value: 'imagery',  label: 'Imagery' },
              ]}
            />
          </TweakSection>

          <TweakSection label="Section page — featured">
            <TweakRadio
              value={tweak.sectionFeatured}
              onChange={(v) => setTweak('sectionFeatured', v)}
              options={[
                { value: 'horizontal', label: 'Horizontal' },
                { value: 'split',      label: 'Split' },
              ]}
            />
          </TweakSection>

          <div style={{
            padding: '10px 14px', margin: '6px 0 4px',
            background: 'rgba(46,111,90,0.06)', borderRadius: 8,
            fontFamily: 'system-ui, sans-serif', fontSize: 11.5, lineHeight: 1.5,
            color: '#2E6F5A',
          }}>
            {view === 'home' && 'Tip: click a category tile (Salud, Belleza, etc.) to preview the section page; click any article to see the full post page.'}
            {view === 'section' && 'Section page — click any article to open the full post.'}
            {view === 'post' && 'Post detail page — Esc or breadcrumb to go back.'}
          </div>
        </TweaksPanel>

        {/* Sticky mini-player — visible on any page while an episode is loaded */}
        <MiniPlayer/>
      </div>
    </LangContext.Provider>
  );
}

window.App = App;

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