/* ============================================================
   RECIPES — index grid + rich detail pages + hosting calculator
   ============================================================ */
function recipeById(id){ return RECIPES.find(r=>r.id===id); }

function RecipesPage(){
  useReveal();
  return (
    <div>
      <PageHero kind="cream" eyebrow="Serving ideas" title={<>Make it look like you <span className="serif-it">hired a chef.</span></>}
        sub="Simple, beautiful ways to serve Mye Noir — most take under 20 minutes and three ingredients."/>
      <section className="section">
        <div className="wrap-wide">
          <div className="recipe-grid">
            {RECIPES.map((r,i)=>(
              <Link to={"/recipes/"+r.id} key={r.id} className="recipe-card reveal" style={{transitionDelay:(i%3*.07)+"s"}}>
                <Photo src={IMG[r.img]} label={r.title.toUpperCase()} className="recipe-img">
                  <span className="recipe-time"><Icon name="clock" size={13}/> {r.time}</span>
                  {r.calculator && <span className="pill solid recipe-calc-flag">Interactive</span>}
                </Photo>
                <div className="recipe-body">
                  <div className="recipe-meta"><span>{r.level}</span><span className="recipe-dot">·</span><span>{r.serves}</span></div>
                  <h3 className="h-sm" style={{marginTop:8}}>{r.title}</h3>
                  <p className="small" style={{marginTop:8,color:"var(--ink-soft)"}}>{r.desc}</p>
                  <span className="btn-link" style={{marginTop:14}}>{r.calculator?"Open calculator":"View recipe"} <Icon name="arrow" size={15} className="arr"/></span>
                </div>
              </Link>
            ))}
          </div>
        </div>
      </section>
      <CtaBand/>
    </div>
  );
}

/* ---- Hosting calculator ---- */
function HostingCalculator(){
  const cart = useCart();
  const { navigate } = useRoute();
  const [guests,setGuests] = useState(8);
  const [style,setStyle] = useState("canape"); // canape | starter | generous
  const perGuest = { canape:3, starter:5, generous:8 }; // canapés per guest
  const canapesPerTin = SERVINGS_PER_TIN;
  const canapes = guests * perGuest[style];
  const tinsNeeded = Math.max(1, Math.ceil(canapes / canapesPerTin));
  // recommend the best-value pack (lowest £/tin) that covers what's needed; ignore the decoy
  const covering = BUNDLES.filter(b=>b.tins>0 && !b.decoy && b.tins>=tinsNeeded);
  const pick = covering.length
    ? covering.sort((a,b)=> perTin(a)-perTin(b))[0]
    : BUNDLES.filter(b=>!b.decoy).sort((a,b)=>b.tins-a.tins)[0];

  return (
    <div className="calc card">
      <div className="calc-controls">
        <div className="calc-field">
          <label>How many guests?</label>
          <div className="calc-stepper">
            <button onClick={()=>setGuests(g=>Math.max(1,g-1))} aria-label="Fewer"><Icon name="minus" size={16}/></button>
            <span className="tnum">{guests}</span>
            <button onClick={()=>setGuests(g=>Math.min(60,g+1))} aria-label="More"><Icon name="plus" size={16}/></button>
          </div>
          <input type="range" min="1" max="40" value={guests} onChange={e=>setGuests(+e.target.value)} className="calc-range" aria-label="Guests"/>
        </div>
        <div className="calc-field">
          <label>How generous?</label>
          <div className="calc-seg" role="radiogroup">
            {[["canape","A few canapés"],["starter","A proper starter"],["generous","Go all out"]].map(([k,l])=>(
              <button key={k} role="radio" aria-checked={style===k} className={style===k?"on":""} onClick={()=>setStyle(k)}>{l}</button>
            ))}
          </div>
        </div>
      </div>

      <div className="calc-out">
        <div className="calc-result">
          <span className="calc-result-n tnum">{tinsNeeded}</span>
          <span className="calc-result-l">tin{tinsNeeded!==1?"s":""} of Mye Noir</span>
          <span className="small" style={{color:"var(--muted)"}}>≈ {canapes} canapés · ~{(canapes/guests).toFixed(0)} per guest</span>
        </div>
        <div className="calc-rec">
          <p className="small" style={{color:"var(--ink-soft)"}}>We'd suggest</p>
          <p className="h-sm" style={{marginTop:2}}>{pick.name}</p>
          <p className="small" style={{color:"var(--muted)",marginBottom:14}}>{pick.tins} × 50g tin{pick.tins>1?"s":""} · {money(pick.price)}</p>
          <button className="btn btn-gold btn-block" onClick={()=>{ cart.setSelected(pick.id); cart.add(pick.id,1); }}>Add {pick.name} · {money(pick.price)}</button>
        </div>
      </div>
      <p className="small calc-note">Guidance only — a 50g tin tops roughly {canapesPerTin} small canapés. Appetites (and occasions) vary.</p>
    </div>
  );
}

function RecipeDetail({ id }){
  useReveal();
  const cart = useCart();
  const r = recipeById(id);
  if(!r) return <RecipesPage/>;
  const others = RECIPES.filter(x=>x.id!==id && !x.calculator).slice(0,3);

  return (
    <div className="recipe-detail">
      <section className="rd-hero">
        <Photo src={IMG[r.img]} className="rd-hero-img"/>
        <div className="rd-hero-veil"></div>
        <div className="wrap-wide rd-hero-inner on-dark">
          <Link to="/recipes" className="rd-back"><Icon name="arrowL" size={16}/> All recipes</Link>
          <h1 className="h-xl" style={{marginTop:14,maxWidth:"20ch"}}>{r.title}</h1>
          <div className="rd-meta">
            <span><Icon name="clock" size={15}/> {r.time}</span>
            <span className="rd-dot">·</span><span>{r.level}</span>
            <span className="rd-dot">·</span><span>{r.serves}</span>
          </div>
        </div>
      </section>

      <section className="section">
        <div className="wrap-wide rd-grid">
          <div className="rd-main">
            <p className="lede reveal">{r.intro}</p>

            {r.calculator ? (
              <div className="reveal" style={{marginTop:30}}><HostingCalculator/></div>
            ) : (
              <React.Fragment>
                {r.ingredients.length>0 && (
                  <div className="rd-block reveal">
                    <h2 className="h-md rd-h">Ingredients</h2>
                    <ul className="rd-ingredients">
                      {r.ingredients.map((ing,i)=>(<li key={i}><span className="rd-tick"><Icon name="check" size={13}/></span>{ing}</li>))}
                    </ul>
                  </div>
                )}
                {r.method.length>0 && (
                  <div className="rd-block reveal">
                    <h2 className="h-md rd-h">Method</h2>
                    <ol className="rd-steps">
                      {r.method.map((step,i)=>(
                        <li key={i}><span className="rd-step-n">{i+1}</span><p>{step}</p></li>
                      ))}
                    </ol>
                  </div>
                )}
              </React.Fragment>
            )}

            {r.tip && (
              <div className="rd-tip reveal">
                <span className="value-ic sm"><Icon name="spoon" size={18}/></span>
                <div><p className="rd-tip-h">Chef's tip</p><p style={{marginTop:4,color:"var(--ink-soft)"}}>{r.tip}</p></div>
              </div>
            )}
          </div>

          {/* sticky buy aside */}
          <aside className="rd-aside">
            <div className="rd-buy card">
              <Photo src={IMG.tin} label="MYE NOIR · 50G" className="rd-buy-img"/>
              <div className="rd-buy-body">
                <p className="eyebrow no-rule">You'll need</p>
                <p className="h-sm" style={{marginTop:6}}>Mye Noir</p>
                <p className="small" style={{color:"var(--muted)",marginTop:2}}>Seaweed caviar · 50g tin</p>
                {r.tins>0 && <p className="rd-need">This recipe uses <b>{r.tins} tin{r.tins>1?"s":""}</b></p>}
                <div className="rd-buy-price"><span className="tnum" style={{fontFamily:"var(--serif)",fontSize:26,fontWeight:600}}>{money(PRODUCT.basePrice)}</span><span className="small" style={{color:"var(--muted)"}}>per tin</span></div>
                <button className="btn btn-gold btn-block" onClick={()=>{ const b = r.tins>=2?"duo":"single"; cart.setSelected(b); cart.add(b,1); }}>
                  <Icon name="cart" size={16}/> Add {r.tins>=2?"2 tins":"to cart"}
                </button>
                <p className="small center" style={{marginTop:12,color:"var(--muted)"}}><Icon name="truck" size={12}/> Free UK delivery on selected orders</p>
              </div>
            </div>
          </aside>
        </div>
      </section>

      {others.length>0 && (
        <section className="section-sm cream-bg">
          <div className="wrap-wide">
            <div className="between" style={{marginBottom:28,flexWrap:"wrap",gap:16}}>
              <h2 className="h-lg">More ways to serve</h2>
              <Link to="/recipes" className="btn btn-ghost">All recipes <Icon name="arrow" size={16} className="arr"/></Link>
            </div>
            <div className="recipe-grid">
              {others.map((o,i)=>(
                <Link to={"/recipes/"+o.id} key={o.id} className="recipe-card reveal" style={{transitionDelay:(i*.07)+"s"}}>
                  <Photo src={IMG[o.img]} label={o.title.toUpperCase()} className="recipe-img">
                    <span className="recipe-time"><Icon name="clock" size={13}/> {o.time}</span>
                  </Photo>
                  <div className="recipe-body">
                    <div className="recipe-meta"><span>{o.level}</span><span className="recipe-dot">·</span><span>{o.serves}</span></div>
                    <h3 className="h-sm" style={{marginTop:8}}>{o.title}</h3>
                  </div>
                </Link>
              ))}
            </div>
          </div>
        </section>
      )}
    </div>
  );
}

Object.assign(window, { RecipesPage, RecipeDetail, HostingCalculator, recipeById });
