// Pantry / Meal Plan / Shopping List screens — with backup code, email menu, currency
const Pantry = ({ mobile = false }) => {
  const [staples, setStaples] = React.useState(['雞蛋','米飯','醬油','蔥','蒜','薑','鹽','糖','米酒']);
  const [today, setToday] = React.useState(['番茄','豆腐']);
  const [v, setV] = React.useState('');
  const [showCode, setShowCode] = React.useState(false);
  const [showRestore, setShowRestore] = React.useState(false);
  const [restoreV, setRestoreV] = React.useState('');
  // Pseudo-deterministic backup code
  const code = React.useMemo(() => {
    const s = (staples.length + today.length) * 7 + 235;
    const letters = ['BBQ','SOY','WOK','TOFU','MISO','CHILI','BASIL','MINT'];
    return `${letters[(s * 3) % letters.length]}-${String(s % 999).padStart(3,'0')}`;
  }, [staples, today]);
  const W = mobile ? 'm' : 'd';

  return (
    <div className={`page page--${W}`}>
      <Header active="pantry" mobile={mobile}/>
      <section className={`pant pant--${W}`}>
        <Eyebrow>Pantry Mode · 我的冰箱</Eyebrow>
        <h1 className="pant__h">記住你的常備食材，<br/><em>每次搜索少打 5 個字。</em></h1>
        <p className="pant__p">把家裡常備的調味料與主食記在這裡。每次搜索時自動帶入，你只需輸入今天買的特殊食材即可。資料儲存在你的瀏覽器，不需要登入。</p>

        <div className="pant__cols">
          <div className="pant__col">
            <h3 className="pant__sh"><Icon name="fridge" size={18}/> 常備食材 <span>{staples.length} 樣</span></h3>
            <p className="pant__hint">這些每天都有 — 醬油、蛋、米、蔥薑蒜…</p>
            <div className="pant__tags">
              {staples.map(s => (
                <span key={s} className="tag tag--lg">
                  {s}<button onClick={()=>setStaples(staples.filter(x=>x!==s))}><Icon name="x" size={12} stroke={2}/></button>
                </span>
              ))}
              <form className="pant__add" onSubmit={e=>{e.preventDefault(); if(v){setStaples([...staples, v]); setV('');}}}>
                <input value={v} onChange={e=>setV(e.target.value)} placeholder="加入常備食材…"/>
                <button><Icon name="plus" size={14} stroke={2}/></button>
              </form>
            </div>
          </div>

          <div className="pant__col">
            <h3 className="pant__sh"><Icon name="sparkles" size={18}/> 今日特殊食材 <span>{today.length} 樣</span></h3>
            <p className="pant__hint">今天剛買的、快過期的、想用掉的…</p>
            <div className="pant__tags">
              {today.map(s => (
                <span key={s} className="tag tag--lg tag--accent">
                  {s}<button onClick={()=>setToday(today.filter(x=>x!==s))}><Icon name="x" size={12} stroke={2}/></button>
                </span>
              ))}
            </div>
            <button className="btn btn--primary pant__cta">
              用「常備 + 今日」搜尋食譜 ({staples.length + today.length} 樣) <Icon name="arrowRight" size={14}/>
            </button>
          </div>
        </div>

        {/* Backup code section — the surprise/delight feature */}
        <div className="bkup">
          <div className="bkup__l">
            <Eyebrow>備份 · 跨裝置同步</Eyebrow>
            <h3 className="bkup__h">不想註冊？用一組代碼帶走你的冰箱。</h3>
            <p className="bkup__p">產生一組短代碼，在另一台手機/電腦輸入即可恢復你的常備食材、收藏食譜、購物清單。零帳號、零密碼、零追蹤。</p>
          </div>
          <div className="bkup__r">
            <div className="bkup__code">
              <span className="bkup__lab">你的備份代碼</span>
              <b>{code}</b>
              <span className="bkup__hint">{staples.length + today.length} 樣食材 · {(staples.length+today.length)*4} 道相關食譜 · 15 個收藏</span>
            </div>
            <div className="bkup__actions">
              <button className="btn btn--primary btn--sm" onClick={()=>setShowCode(true)}><Icon name="share" size={14}/> 顯示 QR Code</button>
              <button className="btn btn--ghost btn--sm" onClick={()=>setShowRestore(true)}>輸入代碼恢復</button>
            </div>
          </div>
        </div>
      </section>

      <Modal open={showCode} onClose={()=>setShowCode(false)} title="掃描 · 在手機上恢復">
        <div className="qr">
          <div className="qr__box">
            <svg viewBox="0 0 100 100" width="180" height="180">
              {/* Stylized QR placeholder */}
              {Array.from({length: 100}).map((_, i) => {
                const x = i % 10, y = Math.floor(i / 10);
                const seed = (x * 7 + y * 13 + code.length * 3) % 100;
                if (seed < 45) return <rect key={i} x={x*10} y={y*10} width="10" height="10" fill="#1A1A1A"/>;
                return null;
              })}
              {/* QR finder squares */}
              <rect x="0" y="0" width="30" height="30" fill="none" stroke="#1A1A1A" strokeWidth="3"/>
              <rect x="10" y="10" width="10" height="10" fill="#1A1A1A"/>
              <rect x="70" y="0" width="30" height="30" fill="none" stroke="#1A1A1A" strokeWidth="3"/>
              <rect x="80" y="10" width="10" height="10" fill="#1A1A1A"/>
              <rect x="0" y="70" width="30" height="30" fill="none" stroke="#1A1A1A" strokeWidth="3"/>
              <rect x="10" y="80" width="10" height="10" fill="#1A1A1A"/>
            </svg>
          </div>
          <div className="qr__r">
            <span className="qr__lab">代碼</span>
            <b>{code}</b>
            <p>用另一台裝置打開 airecipelive.com，到「我的冰箱」→「輸入代碼恢復」貼上即可。</p>
            <span className="qr__exp">代碼有效期 · 30 天</span>
          </div>
        </div>
      </Modal>

      <Modal open={showRestore} onClose={()=>setShowRestore(false)} title="輸入備份代碼">
        <div className="rest">
          <p className="rest__p">在另一台裝置產生的 6–8 位代碼，輸入後即恢復常備食材、收藏與購物清單。</p>
          <input className="rest__in" value={restoreV} onChange={e=>setRestoreV(e.target.value.toUpperCase())} placeholder="例：BBQ-742" />
          <button className="btn btn--primary" onClick={()=>setShowRestore(false)}>恢復資料</button>
          <span className="rest__sec">🔒 端對端 · 我們無法讀取你的資料內容</span>
        </div>
      </Modal>
      <Footer/>
    </div>
  );
};

const MealPlan = ({ mobile = false }) => {
  const W = mobile ? 'm' : 'd';
  const days = ['週一','週二','週三','週四','週五','週六','週日'];
  const meals = ['早','午','晚'];
  const recipes = window.RECIPES;
  const money = useMoney();
  const [showEmail, setShowEmail] = React.useState(false);
  const [emailV, setEmailV] = React.useState('');
  const [sent, setSent] = React.useState(false);

  // Mock TWD prices
  const total = money(1840);
  const perPerson = money(460);

  return (
    <div className={`page page--${W}`}>
      <Header active="mealplan" mobile={mobile}/>
      <section className={`mp mp--${W}`}>
        <Eyebrow>每週膳食計劃 · Phase 2</Eyebrow>
        <h1 className="mp__h">這週 <em>七天</em>，<br/>讓我們替你規劃菜單。</h1>
        <p className="mp__p">告訴我們你的飲食偏好、家庭人數、想避開的食材，系統會生成一週菜單與一張統合採購清單。</p>

        <div className="mp__pref">
          <span className="mp__lab">偏好</span>
          <button className="chip is-on">家常台味</button>
          <button className="chip">減脂高蛋白</button>
          <button className="chip">純素</button>
          <button className="chip is-on">15 分內</button>
          <span className="mp__lab">人數</span>
          <button className="chip is-on">4 人</button>
          <button className="btn btn--ghost btn--sm" style={{marginLeft:'auto'}}><Icon name="sparkles" size={14}/> 重新生成</button>
        </div>

        {!mobile ? (
          <div className="mp__grid">
            <div className="mp__head"></div>
            {days.map(d => <div key={d} className="mp__day">{d}</div>)}
            {meals.map((m, mi) => (
              <React.Fragment key={m}>
                <div className="mp__meal">{m}餐</div>
                {days.map((d, di) => {
                  const r = recipes[(mi*7+di) % recipes.length];
                  return (
                    <div key={d} className="mp__cell">
                      <img src={r.img} alt=""/>
                      <span className="mp__t">{r.title}</span>
                      <span className="mp__m">{r.time}分 · {r.cal}卡</span>
                    </div>
                  );
                })}
              </React.Fragment>
            ))}
          </div>
        ) : (
          <div className="mp__list">
            {days.map((d, di) => (
              <div key={d} className="mp__row">
                <h4>{d}</h4>
                {meals.map((m, mi) => {
                  const r = recipes[(mi*7+di) % recipes.length];
                  return (
                    <div key={m} className="mp__rcell">
                      <img src={r.img} alt=""/>
                      <div><span className="mp__rm">{m}餐</span><b>{r.title}</b><span>{r.time}分 · {r.cal}卡</span></div>
                    </div>
                  );
                })}
              </div>
            ))}
          </div>
        )}

        <div className="mp__foot">
          <div><b>21 餐</b><span>本週菜單</span></div>
          <div>
            <b>{total.sym} {total.num}</b>
            <span>預估採購 · {total.code}</span>
          </div>
          <div><b>{perPerson.sym} {perPerson.num}</b><span>每人每週</span></div>
          <div><b>43 樣</b><span>食材清單</span></div>
          <div className="mp__foot-acts">
            <button className="btn btn--ghost btn--sm" onClick={()=>setShowEmail(true)}>📧 寄給我</button>
            <button className="btn btn--primary"><Icon name="cart" size={14}/> 生成採購清單</button>
          </div>
        </div>

        <div className="mp__nosignup">
          <Icon name="check" size={14} stroke={2.5}/>
          <span>菜單已自動儲存到此瀏覽器 · 不需要註冊。換裝置？到 <a onClick={()=>{}}>我的冰箱 → 備份代碼</a> 即可同步。</span>
        </div>
      </section>

      <Modal open={showEmail} onClose={()=>{setShowEmail(false); setSent(false);}} title="把這份菜單寄給你">
        {!sent ? (
          <div className="rest">
            <p className="rest__p">輸入信箱，我們會把這週的菜單與採購清單寄給你。<b>不訂閱、不發其他信</b>，承諾就是這一封。</p>
            <input className="rest__in" type="email" value={emailV} onChange={e=>setEmailV(e.target.value)} placeholder="your@email.com" />
            <button className="btn btn--primary" onClick={()=>setSent(true)} disabled={!emailV.includes('@')}>寄給我</button>
            <label className="rest__opt"><input type="checkbox"/> 我也想訂閱每週精選食譜（可隨時取消）</label>
          </div>
        ) : (
          <div className="rest rest--ok">
            <div className="rest__check"><Icon name="check" size={36} stroke={2.5}/></div>
            <h4>已寄出 ✓</h4>
            <p>請查看 <b>{emailV}</b> 的收件匣。沒收到？看看垃圾信。</p>
            <button className="btn btn--ghost btn--sm" onClick={()=>{setShowEmail(false); setSent(false);}}>關閉</button>
          </div>
        )}
      </Modal>
      <Footer/>
    </div>
  );
};

const Shopping = ({ mobile = false }) => {
  const W = mobile ? 'm' : 'd';
  const [checked, setChecked] = React.useState(new Set());
  const money = useMoney();
  const list = [
    { c: '蔬菜', items: [
      { n: '中型番茄', q: '6 顆', from: '番茄炒蛋 · 紅酒燉牛肉', p: 90 },
      { n: '洋蔥', q: '3 顆', from: '蛋包飯 · 紅酒燉牛肉', p: 60 },
      { n: '馬鈴薯', q: '4 顆', from: '紅酒燉牛肉 · 烤雞', p: 80 },
      { n: '蒜', q: '1 整顆', from: '蒜香義麵', p: 30 },
    ]},
    { c: '肉品 · 海鮮', items: [
      { n: '雞腿肉', q: '500g', from: '蛋包飯', p: 180 },
      { n: '牛肋條', q: '800g', from: '紅酒燉牛肉', p: 480 },
      { n: '蝦仁', q: '200g', from: '蝦仁炒飯', p: 220 },
    ]},
    { c: '其他', items: [
      { n: '雞蛋', q: '1 盒', from: '番茄炒蛋 · 蛋包飯 · 蝦仁炒飯', p: 95 },
      { n: '紅酒', q: '1 瓶', from: '紅酒燉牛肉', p: 380 },
      { n: '迷迭香', q: '1 小束', from: '香草烤全雞', p: 50 },
    ]},
  ];
  const total = list.reduce((s,c)=>s+c.items.length, 0);
  const done = checked.size;

  // Cost calculation
  const allItems = list.flatMap((cat, ci) => cat.items.map((it, i) => ({...it, key: cat.c+i})));
  const totalTwd = allItems.reduce((s, it) => s + it.p, 0);
  const remainingTwd = allItems.filter(it => !checked.has(it.key)).reduce((s, it) => s + it.p, 0);
  const totalM = money(totalTwd);
  const remainM = money(remainingTwd);

  return (
    <div className={`page page--${W}`}>
      <Header active="shopping" mobile={mobile}/>
      <section className={`sl sl--${W}`}>
        <div className="sl__hd">
          <Eyebrow>購物清單</Eyebrow>
          <h1 className="sl__h">本週要買的，<br/><em>都在這張單上。</em></h1>
        </div>
        <p className="sl__p">統合自 <b>5 道食譜</b> 的食材清單，已自動去重並按超市動線分類。</p>

        <div className="sl__bar">
          <div className="sl__prog">
            <span>{done} / {total} 項</span>
            <div className="sl__pb"><div style={{width:`${done/total*100}%`}}/></div>
          </div>
          <div className="sl__tot">
            <span className="sl__totl">還需要</span>
            <b>{remainM.sym} {remainM.num}</b>
            <span className="sl__totu">/ 共 {totalM.sym} {totalM.num}</span>
          </div>
          <div className="sl__acts">
            <CurrencySwitch compact={mobile}/>
            <button className="btn btn--ghost btn--sm"><Icon name="print" size={14}/> 列印</button>
            <button className="btn btn--ghost btn--sm"><Icon name="share" size={14}/> 分享</button>
          </div>
        </div>

        <div className="sl__list">
          {list.map(cat => (
            <div key={cat.c} className="sl__cat">
              <h3 className="sl__ch">{cat.c}</h3>
              {cat.items.map((it, i) => {
                const key = cat.c + i;
                const m = money(it.p);
                return (
                  <label key={key} className={`sl__it ${checked.has(key)?'is-done':''}`}
                    onClick={()=>{const n=new Set(checked); n.has(key)?n.delete(key):n.add(key); setChecked(n);}}>
                    <span className="ing__cb">{checked.has(key) && <Icon name="check" size={14} stroke={3}/>}</span>
                    <div className="sl__nm">
                      <b>{it.n}</b>
                      <span>{it.from}</span>
                    </div>
                    <span className="sl__price">~{m.sym} {m.num}</span>
                    <span className="sl__q">{it.q}</span>
                  </label>
                );
              })}
            </div>
          ))}
        </div>

        <div className="sl__aff">
          <Icon name="cart" size={18}/>
          <div>
            <b>一鍵下單到 Shopee</b>
            <span>聯盟連結 · 系統會自動帶入清單 · 約省 15 分鐘</span>
          </div>
          <button className="btn btn--primary btn--sm">前往 →</button>
        </div>

        <div className="sl__rate">
          <Icon name="sparkles" size={14}/>
          <span>當前匯率 · 1 TWD ≈ {(CURRENCIES[money(1).code].rate).toFixed(3)} {money(1).code} · 每日自動更新（European Central Bank）</span>
        </div>
      </section>
      <Footer/>
    </div>
  );
};

Object.assign(window, { Pantry, MealPlan, Shopping });
