// Recipe detail — hero, TL;DR, ingredients with servings slider, steps with timer, FAQ
const RecipeDetail = ({ recipe, onBack, mobile = false }) => {
  const r = recipe || window.RECIPES[0];
  const [servings, setServings] = React.useState(r.servings);
  const [checked, setChecked] = React.useState(new Set());
  const [timer, setTimer] = React.useState(null); // { stepN, remaining }
  const [openFaq, setOpenFaq] = React.useState(0);

  React.useEffect(() => {
    if (!timer) return;
    const id = setInterval(() => {
      setTimer(t => {
        if (!t) return null;
        if (t.remaining <= 1) return null;
        return { ...t, remaining: t.remaining - 1 };
      });
    }, 1000);
    return () => clearInterval(id);
  }, [timer]);

  const ratio = servings / r.servings;
  const ingredients = [
    { name: '雞蛋', qty: 3, unit: '顆' },
    { name: '中型番茄', qty: 2, unit: '顆' },
    { name: '洋蔥', qty: 0.5, unit: '顆' },
    { name: '白米飯', qty: 2, unit: '碗' },
    { name: '蔥花', qty: 1, unit: '小把' },
    { name: '生抽', qty: 1, unit: '茶匙' },
    { name: '糖', qty: 0.5, unit: '茶匙' },
    { name: '鹽', qty: null, unit: '少許' },
  ];

  const steps = window.STEPS_TOMATO_EGG;
  const W = mobile ? 'm' : 'd';

  const fmt = (s) => `${Math.floor(s/60)}:${String(s%60).padStart(2,'0')}`;

  return (
    <div className={`page page--${W}`}>
      <Header active="recipes" mobile={mobile}/>
      <article className={`rd rd--${W}`}>
        <div className="bcrumb"><a onClick={onBack}>首頁</a> / <a>中餐</a> / <span>{r.title}</span></div>

        <header className="rd__hd">
          <span className="rd__cat">{r.cat}</span>
          <h1 className="rd__h1">{r.title}</h1>
          <p className="rd__sub">{r.subtitle}</p>
          <div className="rd__meta">
            <div className="rd__author">
              <div className="rd__av">林</div>
              <div>
                <b>主編 · 林書宇</b>
                <span>2026 年 04 月 28 日 · 5 分鐘閱讀</span>
              </div>
            </div>
            <div className="rd__rate">
              {[1,2,3,4,5].map(i => <Icon key={i} name="star" size={16}/>)}
              <span>{r.rating} ({r.reviews} 則評論)</span>
            </div>
          </div>
        </header>

        <div className="rd__hero">
          <img src={r.img} alt={r.title}/>
          <div className="rd__tools">
            <button className="ico-btn"><Icon name="bookmark" size={16}/></button>
            <button className="ico-btn"><Icon name="print" size={16}/></button>
            <button className="ico-btn"><Icon name="share" size={16}/></button>
          </div>
        </div>

        <div className="rd__tldr">
          <h4>TL;DR · 重點摘要</h4>
          <ul>
            <li>快手 <b>15 分鐘</b>完成，一鍋出，不用洗第二個鍋。</li>
            <li>每份 <b>320 大卡</b>，蛋白質 18g，適合上班族午餐便當。</li>
            <li>關鍵技巧：<b>蛋炒七分熟先盛起</b>，回鍋時才不會老。</li>
            <li>缺番茄醬？用 <b>2 顆熟番茄 + 1 茶匙糖 + 半茶匙白醋</b> 自製。</li>
          </ul>
        </div>

        <div className="rd__qf">
          <div><span className="qf__l">時間</span><b>15 分</b></div>
          <div><span className="qf__l">份量</span><b>{r.servings} 人</b></div>
          <div><span className="qf__l">熱量</span><b>320 卡</b></div>
          <div><span className="qf__l">難度</span><b>★ 新手</b></div>
          <div><span className="qf__l">飲食</span><b>素食</b></div>
          <div><span className="qf__l">主料</span><b>番茄 · 蛋</b></div>
        </div>

        <div className={`rd__body rd__body--${W}`}>
          <section className="rd__ing">
            <div className="rd__sh">
              <Eyebrow>食材清單</Eyebrow>
              <h2>準備這些</h2>
            </div>
            <div className="serv">
              <span className="serv__l">份量</span>
              <button onClick={()=>setServings(Math.max(1, servings-2))}>−</button>
              <b>{servings} 人份</b>
              <button onClick={()=>setServings(servings+2)}>+</button>
              <span className="serv__hint">數量已自動換算</span>
            </div>
            <ul className="ing">
              {ingredients.map((i, idx) => (
                <li key={idx} className={checked.has(idx) ? 'is-done' : ''}
                  onClick={() => {
                    const n = new Set(checked);
                    n.has(idx) ? n.delete(idx) : n.add(idx);
                    setChecked(n);
                  }}>
                  <span className="ing__cb">{checked.has(idx) && <Icon name="check" size={14} stroke={3}/>}</span>
                  <span className="ing__n">{i.name}</span>
                  <span className="ing__q">
                    {i.qty !== null ? <b>{(i.qty * ratio).toFixed(i.qty < 1 ? 1 : 0).replace(/\.0$/,'')}</b> : null} {i.unit}
                  </span>
                </li>
              ))}
            </ul>
            <button className="btn btn--ghost btn--sm rd__addcart"><Icon name="cart" size={14}/> 加入購物清單</button>
          </section>

          <section className="rd__steps">
            <div className="rd__sh">
              <Eyebrow>烹飪步驟</Eyebrow>
              <h2>5 步上桌</h2>
            </div>
            <ol className="steps">
              {steps.map(s => (
                <li key={s.n}>
                  <span className="steps__n">{String(s.n).padStart(2,'0')}</span>
                  <div className="steps__b">
                    <p>{s.text}</p>
                    {s.time && (
                      <button className="timer" onClick={() => setTimer({ stepN: s.n, remaining: s.time, total: s.time })}>
                        <Icon name="clock" size={14}/>
                        {timer && timer.stepN === s.n ? `倒計時 ${fmt(timer.remaining)}` : `開始計時 ${s.time/60} 分`}
                      </button>
                    )}
                  </div>
                </li>
              ))}
            </ol>
          </section>

          <section className="rd__tips">
            <div className="rd__sh"><Eyebrow>主編小貼士</Eyebrow><h2>讓這道菜更好吃</h2></div>
            <blockquote>
              <p>炒蛋時火不能太小，油溫要熱、蛋液下鍋立刻起泡，這樣蛋花才會蓬鬆。下番茄前可以先把鍋邊擦一下、補一點油，番茄出汁時才不會黏鍋。</p>
              <cite>— 主編 · 林書宇</cite>
            </blockquote>
          </section>

          <section className="rd__nutr">
            <div className="rd__sh"><Eyebrow>營養資訊</Eyebrow><h2>每份提供</h2></div>
            <div className="nutr">
              {[['熱量','320','kcal'],['蛋白質','18','g'],['碳水','42','g'],['脂肪','9','g'],['糖','6','g'],['鈉','480','mg']].map(([n,v,u])=>(
                <div key={n}><b>{v}<small>{u}</small></b><span>{n}</span></div>
              ))}
            </div>
          </section>

          <section className="rd__faq">
            <div className="rd__sh"><Eyebrow>常見問題</Eyebrow><h2>FAQ</h2></div>
            {[
              ['這道菜可以提前做嗎？','可以，蛋液與番茄分別炒好後冷藏，吃前快速回炒 30 秒即可。建議當天食用，風味最佳。'],
              ['冷藏可以保存多久？','建議 2 天內食用完畢。盛盒冷藏前先放涼，避免水氣回潮。'],
              ['沒有番茄醬可以做嗎？','可以。用 2 顆熟番茄 + 1 茶匙糖 + 半茶匙白醋 慢炒到出汁，效果接近。'],
              ['吃素的可以做嗎？','可以，本食譜本身為素食（含蛋）。如需純素，蛋可換成豆腐丁。'],
            ].map(([q,a],i)=>(
              <div key={i} className={`faq ${openFaq===i?'is-open':''}`} onClick={()=>setOpenFaq(openFaq===i?-1:i)}>
                <div className="faq__q"><span>{q}</span><Icon name="chevronDown" size={18}/></div>
                {openFaq===i && <div className="faq__a">{a}</div>}
              </div>
            ))}
          </section>
        </div>

        <section className="rd__rel">
          <Eyebrow>延伸閱讀</Eyebrow>
          <h2>類似的料理</h2>
          <div className={`grid grid--${W}`}>
            {window.RECIPES.slice(1,5).map(x=><RecipeCard key={x.slug} r={x}/>)}
          </div>
        </section>
      </article>
      <Footer/>
    </div>
  );
};

window.RecipeDetail = RecipeDetail;
