// Shared site shell loader for all multi-page routes.
// Reads ?screen=... or path-based hint. Renders matching screen full-bleed (no canvas).
const { useState, useEffect } = React;

// ───── WP integration: replace prototype mock data with real recipes from DB ─────
// data.jsx assigns window.RECIPES from its mock array. We override here using
// the __WP_RECIPES payload that page-prototype.php injects.
if (window.__WP_RECIPES && window.__WP_RECIPES.length > 0) {
  window.RECIPES = window.__WP_RECIPES;
}
// openRecipe in nav() falls back to /recipes/{slug}/ — already WP-aware.

// ───── P6-2: Footer override with collections + WP-aware links ─────
if (window.__WP_COLLECTIONS && window.__WP_COLLECTIONS.length > 0) {
  window.Footer = function WPFooter() {
    return (
      <footer className="ftr">
        <div className="ftr__top">
          <div className="ftr__brand">
            <div className="ftr__logo">AIRecipe<em>Live</em></div>
            <p>結合 AI 食材搜尋與精選食譜的全球華人美食平台。Tell me what you have. I'll tell you what to cook.</p>
          </div>
          <div className="ftr__cols">
            <div>
              <h5>食譜</h5>
              <a href="/recipes/">所有食譜</a>
              <a href="/cuisine/chinese/">中式家常</a>
              <a href="/cuisine/japanese/">日式</a>
              <a href="/cuisine/italian/">義式</a>
              <a href="/cuisine/korean/">韓式</a>
            </div>
            <div>
              <h5>特選菜單</h5>
              {window.__WP_COLLECTIONS.map(c => (
                <a key={c.slug} href={`/${c.slug}/`}>{c.emoji} {c.title}</a>
              ))}
              <a href="/collections/" style={{color:'#C73E1D',marginTop:'8px',display:'block'}}>看全部 →</a>
            </div>
            <div>
              <h5>工具</h5>
              <a href="/search/">食材搜尋</a>
              <a href="/pantry/">我的冰箱</a>
              <a href="/meal-plan/">膳食計劃</a>
              <a href="/shopping-list/">購物清單</a>
            </div>
            <div>
              <h5>關於</h5>
              <a href="/about/">編輯團隊</a>
              <a href="/about/">編輯方針</a>
              <a href="mailto:hello@airecipelive.com">聯絡我們</a>
              <a href="/llms.txt">llms.txt</a>
            </div>
          </div>
        </div>
        <div className="ftr__bot">
          <span>© 2026 AIRecipeLive · airecipelive.com</span>
          <span>Designed for the global Chinese kitchen.</span>
        </div>
      </footer>
    );
  };
}

// ───── P6-1: Mood Grid → Collections (post-render DOM patch) ─────
// Prototype's <Home> renders mood buttons as <button class="mood">. After React mounts we
// turn each into an anchor pointing to a real WP collection page.
(function () {
  const moodMap = {
    '健身減脂':   '/collection-high-protein/',
    '上班族午餐': '/collection-15-min-recipes/',
    '雨天暖心':   '/collection-warm-soups/',
    '週末甜點':   '/recipes/',
    '家庭聚餐':   '/collection-chinese-classics/',
  };
  function patch() {
    document.querySelectorAll('.mood').forEach(btn => {
      if (btn.dataset.aircWired) return;
      const t = btn.querySelector('.mood__t');
      const text = (t && t.textContent || '').trim();
      const href = moodMap[text];
      if (!href) return;
      btn.dataset.aircWired = '1';
      btn.style.cursor = 'pointer';
      btn.addEventListener('click', () => { window.location.href = href; });
    });
  }
  // Fire once boot completes + watch for re-renders
  if (document.readyState === 'complete' || document.readyState === 'interactive') {
    setTimeout(patch, 100);
  } else {
    window.addEventListener('DOMContentLoaded', () => setTimeout(patch, 100));
  }
  new MutationObserver(patch).observe(document.documentElement, { childList: true, subtree: true });
})();

function getRouteFromPage() {
  // Each page sets window.__SCREEN before this script runs
  return window.__SCREEN || 'home';
}

function SiteApp() {
  const screen = getRouteFromPage();
  const [tags, setTags] = useState(window.__INITIAL_TAGS || []);
  const [recipe, setRecipe] = useState(null);
  const [mobile, setMobile] = useState(false);

  useEffect(() => {
    const check = () => setMobile(window.innerWidth < 768);
    check();
    window.addEventListener('resize', check);
    return () => window.removeEventListener('resize', check);
  }, []);

  const nav = (route, t) => {
    // WP-aware routing — pretty permalinks instead of .html files
    const map = { home: '/', search: '/search/', recipes: '/recipes/',
                  category: '/recipes/', mealplan: '/meal-plan/',
                  pantry: '/pantry/', shopping: '/shopping-list/',
                  about: '/about/', detail: '/recipes/' };
    const url = map[route] || '/';
    if (t && t.length) {
      window.location.href = `${url}?ingredients=${encodeURIComponent(t.join(','))}`;
    } else {
      window.location.href = url;
    }
  };
  const openRecipe = (r) => {
    // Use WP recipe_post permalink if provided, else fallback to /recipes/{slug}/
    window.location.href = r && r.permalink ? r.permalink : `/recipes/${r ? r.slug : ''}/`;
  };

  let view;
  if (screen === 'home') view = <Home onSearch={nav} onOpenRecipe={openRecipe} mobile={mobile} />;
  else if (screen === 'search') view = <SearchResults tags={tags} setTags={setTags} onOpenRecipe={openRecipe} onBack={()=>nav('home')} mobile={mobile} />;
  else if (screen === 'detail') {
    const slug = new URLSearchParams(location.search).get('slug');
    const r = window.RECIPES.find(x => x.slug === slug) || window.RECIPES[0];
    view = <RecipeDetail recipe={r} onBack={()=>nav('home')} mobile={mobile} />;
  }
  else if (screen === 'pantry') view = <Pantry mobile={mobile} />;
  else if (screen === 'mealplan') view = <MealPlan mobile={mobile} />;
  else if (screen === 'shopping') view = <Shopping mobile={mobile} />;
  else if (screen === 'recipes') view = <RecipesArchive onOpenRecipe={openRecipe} mobile={mobile}/>;
  else if (screen === 'about') view = <About mobile={mobile}/>;
  else view = <Home onSearch={nav} onOpenRecipe={openRecipe} mobile={mobile} />;

  return <CurrencyProvider>{view}</CurrencyProvider>;
}

// Recipes archive — simple grid of all
function RecipesArchive({ onOpenRecipe, mobile }) {
  const W = mobile ? 'm' : 'd';
  return (
    <div className={`page page--${W}`}>
      <Header active="recipes" mobile={mobile} onNav={(r)=>{
        const map={home:'index.html',pantry:'pantry.html',shopping:'shopping-list.html',mealplan:'meal-plan.html',about:'about.html',recipes:'recipes.html',category:'recipes.html'};
        window.location.href = map[r]||'index.html';
      }} />
      <section className="srhd">
        <div className="bcrumb"><a href="index.html">首頁</a> / <span>所有食譜</span></div>
        <Eyebrow>食譜總覽</Eyebrow>
        <h1 className="srhd__h">全部 <em>{window.RECIPES.length}</em> 道精選食譜</h1>
      </section>
      <div className="sr sr--no-side" style={{gridTemplateColumns:'1fr', padding:'0 48px 64px'}}>
        <div className={`grid grid--${W}`}>
          {window.RECIPES.map(r => <RecipeCard key={r.slug} r={r} onClick={()=>onOpenRecipe(r)}/>)}
        </div>
      </div>
      <Footer/>
    </div>
  );
}

// About page — E-E-A-T essential
function About({ mobile }) {
  const W = mobile ? 'm' : 'd';
  return (
    <div className={`page page--${W}`}>
      <Header active="about" mobile={mobile} onNav={(r)=>{
        const map={home:'index.html',pantry:'pantry.html',shopping:'shopping-list.html',mealplan:'meal-plan.html',about:'about.html',recipes:'recipes.html'};
        window.location.href = map[r]||'index.html';
      }}/>
      <section className="abt">
        <div className="bcrumb"><a href="index.html">首頁</a> / <span>關於我們</span></div>
        <Eyebrow>關於 AIRecipeLive · Issue 01</Eyebrow>
        <h1 className="abt__h">為全球華人廚房，<br/><em>挑選一道道值得做的菜。</em></h1>
        <p className="abt__lead">我們相信，好食譜不只是食材與步驟的清單，更是一段值得閱讀的故事。AIRecipeLive 結合 AI 食材搜尋與精選食譜，用編輯部的眼光為你過濾資訊雜訊，讓「今天煮什麼」不再是焦慮的問題。</p>

        <div className="abt__team">
          <h2 className="abt__sh">編輯團隊</h2>
          <div className="abt__people">
            <div className="abt__p">
              <div className="abt__av">林</div>
              <h4>林書宇 · 主編</h4>
              <span>10 年食物攝影 · 前《飲食男女》編輯</span>
              <p>負責編輯方針與食譜把關。相信每道家常菜都值得被認真寫一次。</p>
            </div>
            <div className="abt__p">
              <div className="abt__av" style={{background:'#6B7F3E', color:'#fff'}}>陳</div>
              <h4>陳美琪 · 食譜總監</h4>
              <span>家政師 · 米其林餐廳前副廚</span>
              <p>所有食譜均經過她的廚房測試，確保「跟著做就會成功」。</p>
            </div>
            <div className="abt__p">
              <div className="abt__av" style={{background:'#D4A574'}}>黃</div>
              <h4>黃彥廷 · 技術長</h4>
              <span>前 Google 工程師 · AI 搜索系統</span>
              <p>負責食材匹配演算法與 AI 整合，讓技術為廚房服務。</p>
            </div>
          </div>
        </div>

        <div className="abt__values">
          <h2 className="abt__sh">我們的承諾</h2>
          <div className="abt__vlist">
            <div><b>真實可重現</b><span>每道食譜都在我們的廚房做過 3 次以上，照片是真實成品。</span></div>
            <div><b>不販售焦慮</b><span>我們不寫「這 5 道菜你必須會」這種文章。料理是樂趣，不是任務。</span></div>
            <div><b>尊重你的時間</b><span>15 分鐘的就標 15 分鐘。從不誇大，從不藏步驟。</span></div>
            <div><b>無贊助偏見</b><span>所有食譜推薦皆獨立判斷。聯盟連結會明確標示，不影響評選。</span></div>
          </div>
        </div>

        <div className="abt__contact">
          <h3>有想分享的家常菜？</h3>
          <p>我們歡迎讀者投稿。寄信到 <a href="mailto:hello@airecipelive.com">hello@airecipelive.com</a>。</p>
        </div>
      </section>
      <Footer/>
    </div>
  );
}

window.RecipesArchive = RecipesArchive;
window.About = About;
window.SiteApp = SiteApp;
