function MenuEngineering() {
  const { L, lang, fmt, recipes, invMap, go, target } = useMizo();
  const rows = recipes.map((r) => ({ r, c: recipeCost(r, invMap) }));
  const avgSold = rows.reduce((s, x) => s + x.r.sold, 0) / rows.length;
  const avgM = rows.reduce((s, x) => s + x.c.margin * x.r.sold, 0) / rows.reduce((s, x) => s + x.r.sold, 0);
  const cls = (x) => (x.r.sold >= avgSold ? (x.c.margin >= avgM ? 'star' : 'horse') : x.c.margin >= avgM ? 'puzzle' : 'dog');
  const Q = {
    star: { n: L('Stars', 'Vedettes'), d: L('Popular and profitable — protect them', 'Populaires et rentables — à protéger'), tone: 'pos', act: L('Keep recipe and price; feature them', 'Garder recette et prix; mettre en avant') },
    horse: { n: L('Workhorses', 'Piliers'), d: L('Popular, thin margin — nudge price or portion', 'Populaires, marge mince — ajuster prix ou portion'), tone: 'warn', act: L('Raise price slightly or trim cost', 'Hausser un peu le prix ou réduire le coût') },
    puzzle: { n: L('Puzzles', 'Énigmes'), d: L('Profitable, under-ordered — promote them', 'Rentables, peu commandés — à promouvoir'), tone: 'neutral', act: L('Better menu spot, staff upsell', 'Meilleure place au menu, suggestion du personnel') },
    dog: { n: L('Dogs', 'Poids morts'), d: L('Low sales, low margin — rethink', 'Peu vendus, marge faible — à repenser'), tone: 'neg', act: L('Rework, reprice or remove', 'Revoir, réévaluer ou retirer') },
  };
  const maxS = Math.max(...rows.map((x) => x.r.sold)) * 1.08, maxM = Math.max(...rows.map((x) => x.c.margin)) * 1.1;
  return (
    <div className="page">
      <PageHead sub={L('Each dish placed by how often it sells and how much it earns per plate.', 'Chaque plat placé selon sa popularité et ce qu’il rapporte par assiette.')} />
      <SeeAlso k="menuEng" />
      <section className="grid-2-1">
        <div className="panel">
          <div className="panel-head"><div><h3>{L('Popularity × margin', 'Popularité × marge')}</h3><p className="muted">{L('Lines mark your menu averages', 'Les lignes marquent les moyennes du menu')} · {fmt.num(Math.round(avgSold))} {L('sold', 'vendus')} · {fmt.money(avgM)}</p></div></div>
          <div className="scatter">
            <span className="sc-q tl">{Q.puzzle.n}</span><span className="sc-q tr">{Q.star.n}</span><span className="sc-q bl">{Q.dog.n}</span><span className="sc-q br">{Q.horse.n}</span>
            <div className="sc-v" style={{ left: (avgSold / maxS) * 100 + '%' }}></div><div className="sc-h" style={{ bottom: (avgM / maxM) * 100 + '%' }}></div>
            {rows.map((x) => (
              <button key={x.r.id} className={'sc-dot ' + cls(x) + (x.r.sold / maxS > 0.6 ? ' l' : '')} style={{ left: (x.r.sold / maxS) * 100 + '%', bottom: (x.c.margin / maxM) * 100 + '%' }} onClick={() => go('menu', { recipe: x.r.id })} title={x.r.name[lang]}>
                <i></i><span>{x.r.name[lang]}</span>
              </button>
            ))}
            <span className="sc-ax x">{L('Units sold / month →', 'Unités vendues / mois →')}</span><span className="sc-ax y">{L('Margin per plate →', 'Marge par assiette →')}</span>
          </div>
        </div>
        <div className="panel">
          <h3>{L('What each group needs', 'Ce que chaque groupe demande')}</h3>
          {['star', 'horse', 'puzzle', 'dog'].map((k) => (
            <div key={k} className="set-row col">
              <div className="dr-row"><Pill tone={Q[k].tone}>{Q[k].n}</Pill><span className="muted sm">{Q[k].d}</span></div>
              <div className="q-items">{rows.filter((x) => cls(x) === k).map((x) => <button key={x.r.id} className="chip" onClick={() => go('menu', { recipe: x.r.id })}>{x.r.name[lang]}</button>)}</div>
            </div>
          ))}
        </div>
      </section>
      <div className="panel panel-flush">
        <div className="table-scroll">
          <table className="table mtable">
            <thead><tr><th>{L('Dish', 'Plat')}</th><th className="num">{L('Sold', 'Vendus')}</th><th className="num">{L('Margin', 'Marge')}</th><th className="num hide-sm">{L('Food cost', 'Coût')}</th><th>{L('Group', 'Groupe')}</th><th className="hide-md">{L('Suggested move', 'Action suggérée')}</th></tr></thead>
            <tbody>{rows.slice().sort((a, b) => b.c.monthly - a.c.monthly).map((x) => (
              <tr key={x.r.id} className="clickable" onClick={() => go('menu', { recipe: x.r.id })}>
                <td className="cell-main">{x.r.name[lang]}</td><td className="num tnum">{fmt.num(x.r.sold)}</td><td className="num tnum">{fmt.money(x.c.margin)}</td>
                <td className="num hide-sm"><Pill tone={fcTone(x.c.fc, target)}>{fmt.pct(x.c.fc)}</Pill></td><td><Pill tone={Q[cls(x)].tone}>{Q[cls(x)].n}</Pill></td><td className="muted hide-md">{Q[cls(x)].act}</td>
              </tr>
            ))}</tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

function ChannelPricing() {
  const { L, lang, fmt, O, recipes, invMap, target, toast } = useMizo();
  const [mk, setMk] = React.useState({ uber: 15, dd: 15 });
  const [ch, setCh] = React.useState('uber');
  const chan = O.channels.find((c) => c.k === ch);
  const rows = recipes.map((r) => {
    const c = recipeCost(r, invMap), price = Math.round(r.price * (1 + mk[ch] / 100) * 20) / 20 - 0.0, net = price * (1 - chan.fee / 100);
    return { r, c, price, net, m: net - c.total, fc: (c.total / net) * 100 };
  });
  const losing = rows.filter((x) => x.m < x.c.margin * 0.8).length;
  const avgNet = rows.reduce((s, x) => s + x.m * x.r.sold, 0) / rows.reduce((s, x) => s + x.c.margin * x.r.sold, 0);
  return (
    <div className="page">
      <PageHead sub={L('Delivery apps take a commission. Set a markup per channel so every plate still pays.', 'Les applis prennent une commission. Fixez une majoration par canal pour que chaque assiette rapporte.')}>
        <Seg size="sm" value={ch} onChange={setCh} options={[['uber', 'Uber Eats'], ['dd', 'DoorDash']]} />
      </PageHead>
      <section className="grid-1-2">
        <div className="panel">
          <h3>{chan.name[lang]}</h3>
          <div className="set-row"><div><div>{L('Commission', 'Commission')}</div><div className="muted sm">{L('From your contract', 'Selon votre contrat')}</div></div><b className="big tnum">{fmt.pct(chan.fee)}</b></div>
          <div className="set-row col">
            <div className="dr-row"><div><div>{L('Menu markup', 'Majoration du menu')}</div><div className="muted sm">{L('Added on top of in-store prices', 'Ajoutée aux prix en salle')}</div></div><b className="big tnum">{mk[ch]}%</b></div>
            <input type="range" className="range" min="0" max="35" value={mk[ch]} onChange={(e) => setMk({ ...mk, [ch]: Number(e.target.value) })} />
          </div>
          <div className="set-row"><div><div>{L('Margin kept vs. in-store', 'Marge conservée vs en salle')}</div><div className="muted sm">{L('Weighted by sales', 'Pondérée par les ventes')}</div></div><b className={'big tnum ' + (avgNet >= 0.9 ? 'txt-pos' : avgNet >= 0.75 ? 'txt-warn' : 'txt-neg')}>{fmt.pct(avgNet * 100)}</b></div>
          <div className="suggest"><Icon n="sparkle" /><div>{losing ? L(`${losing} dishes keep less than 80% of their in-store margin at this markup.`, `${losing} plats gardent moins de 80 % de leur marge en salle.`) : L('Every dish keeps at least 80% of its in-store margin.', 'Chaque plat garde au moins 80 % de sa marge en salle.')}</div></div>
          <button className="btn btn-primary" onClick={() => toast(L(`${chan.name.en} prices saved — they’ll sync once your POS is connected`, `Prix ${chan.name.fr} enregistrés — synchronisés à la connexion du PDV`))}><Icon n="floppy-disk" />{L('Save channel prices', 'Enregistrer les prix')}</button>
        </div>
        <div className="panel panel-flush">
          <div className="table-scroll">
            <table className="table mtable">
              <thead><tr><th>{L('Dish', 'Plat')}</th><th className="num hide-sm">{L('In-store', 'En salle')}</th><th className="num">{chan.name[lang]}</th><th className="num hide-sm">{L('After fee', 'Après frais')}</th><th className="num">{L('Margin', 'Marge')}</th><th className="num">{L('Food cost', 'Coût')}</th></tr></thead>
              <tbody>{rows.map((x) => (
                <tr key={x.r.id}><td className="cell-main">{x.r.name[lang]}</td><td className="num tnum hide-sm">{fmt.money(x.r.price)}</td><td className="num tnum">{fmt.money(x.price)}</td><td className="num tnum hide-sm">{fmt.money(x.net)}</td>
                  <td className="num"><span className={'tnum ' + (x.m < x.c.margin * 0.8 ? 'txt-neg' : '')}>{fmt.money(x.m)}</span><div className="cell-sub">{L('in-store', 'en salle')} {fmt.money(x.c.margin)}</div></td>
                  <td className="num"><Pill tone={fcTone(x.fc, target)}>{fmt.pct(x.fc)}</Pill></td></tr>
              ))}</tbody>
            </table>
          </div>
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { MenuEngineering, ChannelPricing });
