function Recipes({ focus }) {
  const { L, lang, fmt, D, inv, invMap, recipes, setRecipes, target, toast } = useMizo();
  const [sel, setSel] = React.useState(focus || 'chpita');
  const [cat, setCat] = React.useState('all');
  const [sort, setSort] = React.useState('profit');
  const [adding, setAdding] = React.useState(false);
  React.useEffect(() => { if (focus) setSel(focus); }, [focus]);
  const list = recipes.filter((r) => cat === 'all' || r.cat === cat).map((r) => ({ r, c: recipeCost(r, invMap) }))
    .sort((a, b) => (sort === 'profit' ? b.c.monthly - a.c.monthly : b.c.fc - a.c.fc));
  const r = recipes.find((x) => x.id === sel) || recipes[0];
  const c = recipeCost(r, invMap);
  const upd = (patch) => setRecipes(recipes.map((x) => (x.id === r.id ? { ...x, ...patch } : x)));
  const setLine = (idx, qty) => upd({ lines: r.lines.map((l, i) => (i === idx ? { ...l, qty } : l)) });
  const suggested = Math.ceil((c.total / (target / 100)) * 4) / 4 - 0.05;
  const tone = fcTone(c.fc, target);
  const avail = inv.filter((i) => !r.lines.some((l) => l.ing === i.id));
  const segs = c.lines.slice().sort((a, b) => b.cost - a.cost);

  return (
    <div className="page">
      <PageHead title={L('Recipes & food costs', 'Recettes et coûts')} sub={L('Know exactly what every plate costs you — and what it earns.', 'Sachez ce que chaque assiette vous coûte et vous rapporte.')}>
        <button className="btn btn-primary" onClick={() => setAdding(true)}><Icon n="plus" />{L('New recipe', 'Nouvelle recette')}</button>
      </PageHead>
      <div className="recipes">
        <aside className="panel panel-flush rlist">
          <div className="rlist-tools">
            <select className="input" value={cat} onChange={(e) => setCat(e.target.value)}><option value="all">{L('All dishes', 'Tous les plats')}</option>{Object.entries(D.recipeCats).map(([k, v]) => <option key={k} value={k}>{v[lang]}</option>)}</select>
            <Seg size="sm" value={sort} onChange={setSort} options={[['profit', L('Profit', 'Profit')], ['fc', L('Cost %', 'Coût %')]]} />
          </div>
          <ul>
            {list.map(({ r: x, c: cx }) => (
              <li key={x.id}><button className={'rlist-item' + (x.id === r.id ? ' on' : '')} onClick={() => setSel(x.id)}>
                <div className="rlist-main"><span>{x.name[lang]}</span><span className="muted sm">{fmt.money(x.price)} · {fmt.money0(cx.monthly)}{L('/mo', '/mois')}</span></div>
                <Pill tone={fcTone(cx.fc, target)}>{fmt.pct(cx.fc)}</Pill>
              </button></li>
            ))}
          </ul>
        </aside>

        <section className="panel reditor">
          <div className="red-head">
            <div><div className="card-kicker">{D.recipeCats[r.cat][lang]} · {fmt.num(r.sold)} {L('sold last month', 'vendus le mois dernier')}</div><h2>{r.name[lang]}</h2></div>
            <div className="field price-field"><label>{L('Menu price', 'Prix au menu')}</label>
              <div className="money-input"><span>$</span><input className="input" type="number" step="0.05" value={r.price} onChange={(e) => upd({ price: Number(e.target.value) })} /></div>
            </div>
          </div>

          <div className="red-stats">
            <Stat label={L('Cost per plate', 'Coût par assiette')} value={fmt.money(c.total)} />
            <Stat label={L('Food cost', 'Coût alimentaire')} value={fmt.pct(c.fc)} tone={tone}>{L('Target', 'Cible')} {fmt.pct(target)}</Stat>
            <Stat label={L('Profit per plate', 'Profit par assiette')} value={fmt.money(c.margin)} />
            <Stat label={L('Profit per month', 'Profit par mois')} value={fmt.money0(c.monthly)} tone="acc" />
          </div>

          {tone !== 'pos' ? (
            <div className="suggest">
              <Icon n="sparkle" s="1.2rem" />
              <div>{L(<>To hit your {fmt.pct(target)} target, charge <b>{fmt.money(suggested)}</b>. That adds <b>{fmt.money0((suggested - r.price) * r.sold)}</b> a month.</>, <>Pour atteindre {fmt.pct(target)}, demandez <b>{fmt.money(suggested)}</b>. Cela ajoute <b>{fmt.money0((suggested - r.price) * r.sold)}</b> par mois.</>)}</div>
              <button className="btn btn-primary" onClick={() => { upd({ price: suggested }); toast(L(`${r.name.en} now ${fmt.money(suggested)}`, `${r.name.fr} : ${fmt.money(suggested)}`)); }}>{L('Apply price', 'Appliquer')}</button>
            </div>
          ) : null}

          <div className="costbar" title={L('Where the cost goes', 'Répartition du coût')}>
            {segs.map((l, i) => <div key={l.ing} style={{ flex: l.cost, opacity: 1 - i * 0.09 }} title={l.ingObj.name[lang]}></div>)}
            {r.pack ? <div className="pack" style={{ flex: r.pack }}></div> : null}
          </div>
          <div className="costbar-legend muted sm">
            {segs.slice(0, 3).map((l) => <span key={l.ing}>{l.ingObj.name[lang]} {fmt.pct((l.cost / c.total) * 100)}</span>)}
          </div>

          <div className="table-scroll">
            <table className="table mtable">
              <thead><tr><th>{L('Ingredient', 'Ingrédient')}</th><th>{L('Portion', 'Portion')}</th><th className="num hide-sm">{L('Unit cost', 'Coût unit.')}</th><th className="num">{L('Cost', 'Coût')}</th><th></th></tr></thead>
              <tbody>
                {c.lines.map((l, idx) => (
                  <tr key={l.ing}>
                    <td><div className="cell-main">{l.ingObj.name[lang]}</div>{l.ingObj.trend >= 8 ? <div className="cell-sub txt-neg">▲ {fmt.pct(l.ingObj.trend)} {L('this month', 'ce mois-ci')}</div> : null}</td>
                    <td><div className="portion"><input className="input" type="number" step={l.ingObj.unit === 'ea' ? 0.5 : 0.005} value={l.qty} onChange={(e) => setLine(idx, Number(e.target.value))} /><span className="muted">{l.ingObj.unit}</span></div></td>
                    <td className="num tnum muted hide-sm">{fmt.money(l.ingObj.cost)}/{l.ingObj.unit}</td>
                    <td className="num tnum">{fmt.money(l.cost)}</td>
                    <td className="num"><button className="btn btn-icon btn-ghost" aria-label="Remove" onClick={() => upd({ lines: r.lines.filter((_, i) => i !== idx) })}><Icon n="x" /></button></td>
                  </tr>
                ))}
                <tr className="row-soft">
                  <td><div className="cell-main">{L('Packaging & sauces', 'Emballage et sauces')}</div></td>
                  <td><div className="portion"><input className="input" type="number" step="0.05" value={r.pack} onChange={(e) => upd({ pack: Number(e.target.value) })} /><span className="muted">$</span></div></td>
                  <td className="hide-sm"></td><td className="num tnum">{fmt.money(r.pack)}</td><td></td>
                </tr>
              </tbody>
              <tfoot><tr><td colSpan="3" className="hide-sm"><b>{L('Total cost per plate', 'Coût total par assiette')}</b></td><td className="num tnum"><b>{fmt.money(c.total)}</b></td><td></td></tr></tfoot>
            </table>
          </div>
          <div className="add-line">
            <select className="input" value="" onChange={(e) => e.target.value && upd({ lines: [...r.lines, { ing: e.target.value, qty: invMap[e.target.value].unit === 'ea' ? 1 : 0.05 }] })}>
              <option value="">+ {L('Add an ingredient…', 'Ajouter un ingrédient…')}</option>
              {avail.map((i) => <option key={i.id} value={i.id}>{i.name[lang]}</option>)}
            </select>
          </div>
        </section>
      </div>
      <NewRecipeModal open={adding} onClose={() => setAdding(false)} onCreate={(id) => setSel(id)} />
    </div>
  );
}

function NewRecipeModal({ open, onClose, onCreate }) {
  const { L, lang, D, recipes, setRecipes } = useMizo();
  const [f, setF] = React.useState({ name: '', cat: 'plates', price: '' });
  const ok = f.name.trim() && Number(f.price) > 0;
  const save = () => {
    const id = 'r' + Date.now();
    setRecipes([...recipes, { id, name: { en: f.name, fr: f.name }, cat: f.cat, price: Number(f.price), sold: 0, lines: [], pack: 0.25 }]);
    onCreate(id); setF({ name: '', cat: 'plates', price: '' }); onClose();
  };
  return (
    <Modal open={open} onClose={onClose} title={L('New recipe', 'Nouvelle recette')} actions={<><button className="btn btn-secondary" onClick={onClose}>{L('Cancel', 'Annuler')}</button><button className="btn btn-primary" disabled={!ok} onClick={save}>{L('Create & add ingredients', 'Créer et ajouter')}</button></>}>
      <div className="form-grid">
        <div className="field span-2"><label>{L('Dish name', 'Nom du plat')}</label><input className="input" autoFocus placeholder={L('e.g. Bifteki plate', 'ex. Assiette bifteki')} value={f.name} onChange={(e) => setF({ ...f, name: e.target.value })} /></div>
        <div className="field"><label>{L('Category', 'Catégorie')}</label><select className="input" value={f.cat} onChange={(e) => setF({ ...f, cat: e.target.value })}>{Object.entries(D.recipeCats).map(([k, v]) => <option key={k} value={k}>{v[lang]}</option>)}</select></div>
        <div className="field"><label>{L('Menu price (CAD)', 'Prix (CAD)')}</label><input className="input" type="number" step="0.05" value={f.price} onChange={(e) => setF({ ...f, price: e.target.value })} /></div>
      </div>
    </Modal>
  );
}
window.Recipes = Recipes;
