function FinMenu() {
  const { L, lang, fmt, recipes, invMap, go } = useMizo();
  const rows = recipes.map((r) => ({ r, c: recipeCost(r, invMap) })).sort((a, b) => b.c.monthly - a.c.monthly);
  const tot = rows.reduce((s, x) => s + x.c.monthly, 0); let cum = 0;
  return (
    <>
      <div className="page">
        <PageHead sub={L('Which dishes actually pay the bills. Menu prices minus recipe cost, times what sold.', 'Quels plats paient vraiment les factures. Prix moins coût de recette, fois les ventes.')} />
      <SeeAlso k="finMenu" />
        <div className="panel panel-flush">
          <div className="panel-head pad"><div><h3>{L('Profit contribution', 'Contribution au profit')}</h3><p className="muted">{L('Last 30 days · before labour and overhead', '30 derniers jours · avant main-d’œuvre et frais')} · {fmt.money0(tot)}</p></div><Prov k="e" /></div>
          <div className="table-scroll">
            <table className="table mtable">
              <thead><tr><th>{L('Dish', 'Plat')}</th><th className="num">{L('Margin / plate', 'Marge / assiette')}</th><th className="num hide-sm">{L('Sold', 'Vendus')}</th><th className="num">{L('Contribution', 'Contribution')}</th><th className="hide-sm">{L('Running share', 'Part cumulée')}</th></tr></thead>
              <tbody>{rows.map((x) => { cum += x.c.monthly; const p = (cum / tot) * 100; return (
                <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.money(x.c.margin)}</td><td className="num tnum hide-sm">{fmt.num(x.r.sold)}</td><td className="num tnum">{fmt.money0(x.c.monthly)}</td>
                  <td className="hide-sm"><div className="mixbar"><div className="hbar-track"><div className={'hbar-fill' + (p <= 80 ? ' first' : '')} style={{ width: p + '%' }}></div></div><span className="tnum muted sm">{fmt.pct(p)}</span></div></td></tr>
              ); })}</tbody>
            </table>
          </div>
        </div>
      </div>
      <MenuEngineering />
    </>
  );
}

function FinAP() {
  const { L, lang, fmt, D, F, invoices, setInvoices, ops, toast, go, calc } = useMizo();
  const open = invoices.filter((v) => v.status !== 'paid').map((v) => ({ ...v, d: v.status === 'overdue' ? v.dueIn : v.dueIn }));
  const B = [[L('Overdue', 'En retard'), (x) => x.d < 0, 'neg'], [L('Due in 0–7 days', 'Dû dans 0–7 jours'), (x) => x.d >= 0 && x.d <= 7, 'warn'], [L('Due in 8–14 days', 'Dû dans 8–14 jours'), (x) => x.d > 7 && x.d <= 14, 'neutral'], [L('Due in 15+ days', 'Dû dans 15 jours et +'), (x) => x.d > 14, 'neutral']];
  const tot = open.reduce((s, x) => s + x.amount, 0), dpo = tot / (F.cogsCalc.purch / 28);
  const sup = (id) => D.suppliers.find((s) => s.id === id).name;
  const bySup = D.suppliers.map((s) => ({ s, v: open.filter((x) => x.sup === s.id).reduce((t, x) => t + x.amount, 0) })).filter((x) => x.v);
  return (
    <div className="page">
      <PageHead sub={L('Supplier invoices you still owe, how old they are, and what’s due next.', 'Les factures fournisseurs à payer, leur âge et ce qui vient à échéance.')}><button className="btn btn-secondary" onClick={() => go('purchasing', { tab: 'scan' })}><Icon n="scan" />{L('Check new invoices', 'Vérifier les nouvelles factures')}</button></PageHead>
      <section className="kpis">
        <Metric hero ic="receipt" label={L('Accounts payable', 'Comptes fournisseurs')} value={fmt.money0(tot)} sub={open.length + ' ' + L('invoices', 'factures')} prov="v" onClick={() => calc({ title: L('Accounts payable', 'Comptes fournisseurs'), value: fmt.money(tot), prov: 'v', formula: L('Σ unpaid supplier invoices entered in MIZO', 'Σ factures fournisseurs impayées dans MIZO'), rows: { head: [L('Invoice', 'Facture'), L('Due', 'Échéance'), L('Amount', 'Montant')], body: open.map((x) => [x.id + ' · ' + sup(x.sup), x.d < 0 ? L('overdue', 'en retard') : x.d + ' ' + L('days', 'j'), fmt.money(x.amount)]) }, notes: [L('Utility bills and rent are scheduled in Cash flow, not here.', 'Énergie et loyer sont dans Trésorerie.')], to: ['finance', 'cash'], toLabel: L('Open cash flow', 'Ouvrir la trésorerie') })} />
        {B.slice(0, 2).map(([n, f, t]) => <Metric key={n} ic={t === 'neg' ? 'warning' : 'clock'} label={n} value={fmt.money0(open.filter(f).reduce((s, x) => s + x.amount, 0))} sub={open.filter(f).length + ' ' + L('invoices', 'factures')} prov="v" onClick={() => go('purchasing', { tab: 'invoices' })} />)}
        <Metric ic="calendar-check" label={L('Days payable outstanding', 'Délai moyen de paiement')} value={fmt.num(Math.round(dpo * 10) / 10)} sub={L('days of purchases unpaid', 'jours d’achats impayés')} prov="e" onClick={() => calc({ title: L('Days payable outstanding', 'Délai de paiement'), value: fmt.num(Math.round(dpo * 10) / 10), prov: 'e', formula: L('Accounts payable ÷ average daily purchases', 'Comptes fournisseurs ÷ achats quotidiens moyens'), inputs: [{ label: L('Accounts payable', 'Comptes fournisseurs'), v: fmt.money0(tot), prov: 'v' }, { op: '÷', label: L('Purchases per day, October', 'Achats par jour, octobre'), v: fmt.money0(F.cogsCalc.purch / 28), prov: 'v' }] })} />
      </section>
      <section className="grid-1-2">
        <div className="panel"><div className="panel-head"><div><h3>{L('By supplier', 'Par fournisseur')}</h3></div></div><HBars items={bySup.map((x) => ({ label: x.s.name, v: x.v, sub: L('Net', 'Net') + ' ' + ((ops.supInfo[x.s.id] || {}).terms || '—') + ' ' + L('days', 'jours') }))} fmtv={fmt.money0} /></div>
        <div className="panel panel-flush">
          <div className="table-scroll">
            <table className="table mtable">
              <thead><tr><th>{L('Invoice', 'Facture')}</th><th className="hide-sm">{L('Dated', 'Datée')}</th><th>{L('Due', 'Échéance')}</th><th className="num">{L('Amount', 'Montant')}</th><th></th></tr></thead>
              <tbody>{open.sort((a, b) => a.d - b.d).map((x) => { const b = B.find(([, f]) => f(x)); return (
                <tr key={x.id}><td><div className="cell-main">{x.id}</div><div className="cell-sub">{sup(x.sup)}</div></td><td className="tnum hide-sm">{fmt.date(x.date)}</td><td><Pill tone={b[2]}>{x.d < 0 ? L(`${-x.d} days late`, `${-x.d} j de retard`) : x.d === 0 ? L('Today', 'Aujourd’hui') : L(`in ${x.d} days`, `dans ${x.d} j`)}</Pill></td><td className="num tnum">{fmt.money(x.amount)}</td>
                  <td><button className="btn btn-ghost" onClick={() => { setInvoices(invoices.map((v) => (v.id === x.id ? { ...v, status: 'paid' } : v))); toast(L(`${x.id} marked paid`, `${x.id} marquée payée`)); }}>{L('Mark paid', 'Payée')}</button></td></tr>
              ); })}</tbody>
            </table>
          </div>
        </div>
      </section>
      <span className="muted sm">{L('“Mark paid” records the payment in MIZO only — pay suppliers from your bank as usual.', '« Payée » enregistre le paiement dans MIZO seulement — payez par votre banque comme d’habitude.')}</span>
    </div>
  );
}

function FinForecast() {
  const { L, lang, fmt, F, O, calc } = useMizo();
  const mk = monthsK(), pk = pyK();
  const g = [9, 10, 11].reduce((s, i) => s + (mk[i].rev - pk[i].rev) / pk[i].rev, 0) / 3;
  const rest = O.forecast.slice(0, 3).reduce((s, f) => s + f.rev, 0);
  const octFull = mk[11].rev + rest;
  const margin = [9, 10, 11].reduce((s, i) => s + mk[i].opPct, 0) / 3;
  const fc = [{ l: F.months[11].label[lang] + ' ' + L('(full)', '(complet)'), v: octFull, w: 0.015, base: L(`Oct 1–28 actual + Oct 29–31 daily forecast (${fmt.money0(rest)})`, `Réel 1–28 oct. + prévision 29–31 oct. (${fmt.money0(rest)})`), py: F.py[11].rev * (31 / 28) }, ...[0, 1, 2].map((i, k) => ({ l: F.months[i].label[lang] + ' ' + (i === 2 ? '2027' : '2026'), v: F.months[i].rev * (1 + g), w: 0.05 + k * 0.02, base: L(`${F.months[i].label.en} 2025 actual ${fmt.money0(F.months[i].rev)} × (1 + ${fmt.pct(g * 100)})`, `${F.months[i].label.fr} 2025 réel ${fmt.money0(F.months[i].rev)} × (1 + ${fmt.pct(g * 100)})`), py: F.months[i].rev }))];
  const labels = [...F.months.slice(0, 11).map((m) => m.label[lang]), ...fc.map((x) => x.l.split(' ')[0])];
  const act = [...mk.slice(0, 11).map((x) => x.rev), null, null, null, null];
  const fcs = [...Array(10).fill(null), mk[10].rev, ...fc.map((x) => x.v)];
  const lo = [...Array(10).fill(null), mk[10].rev, ...fc.map((x) => x.v * (1 - x.w))], hi = [...Array(10).fill(null), mk[10].rev, ...fc.map((x) => x.v * (1 + x.w))];
  const method = { title: L('How the forecast works', 'Comment la prévision fonctionne'), value: fmt.pct(g * 100), prov: 'e', formula: L('Next month = same month last year × (1 + average growth of the last 3 months)', 'Mois suivant = même mois l’an dernier × (1 + croissance moyenne des 3 derniers mois)'), rows: { head: [L('Month', 'Mois'), '2026', '2025', L('Growth', 'Croissance')], body: [9, 10, 11].map((i) => [F.months[i].label[lang], fmt.money0(mk[i].rev), fmt.money0(pk[i].rev), fmt.pct(((mk[i].rev - pk[i].rev) / pk[i].rev) * 100)]) }, notes: [L('The range widens the further out we look. Holidays and weather can move a month by ±5%.', 'La fourchette s’élargit avec le temps. Fêtes et météo peuvent faire varier un mois de ±5 %.'), L('This is a simple seasonal model — it will be replaced by POS history once connected.', 'Modèle saisonnier simple — il sera remplacé par l’historique du PDV.')] };
  return (
    <div className="page">
      <PageHead sub={L('What the next three months should bring in, based on last year and how you’re trending.', 'Ce que les trois prochains mois devraient rapporter, selon l’an dernier et la tendance.')}><button className="btn btn-secondary" onClick={() => calc(method)}><Icon n="calculator" />{L('How it works', 'Comment ça marche')}</button></PageHead>
      <SeeAlso k="finFc" />
      <ProvLegend />
      <section className="kpis">
        <Metric hero ic="calendar-check" label={L('October, full month', 'Octobre, mois complet')} value={fmt.money0(octFull)} sub={L('28 days actual + 3 forecast', '28 jours réels + 3 prévus')} prov="e" onClick={() => calc({ ...method, title: L('October full month', 'Octobre complet'), value: fmt.money0(octFull), formula: fc[0].base })} />
        <Metric ic="trend-up" label={L('Growth trend', 'Tendance de croissance')} value={'+' + fmt.pct(g * 100)} sub={L('vs last year, 3-month avg', 'vs l’an dernier, moy. 3 mois')} prov="v" onClick={() => calc(method)} />
        <Metric ic="snowflake" label={L('Next 3 months', '3 prochains mois')} value={fmt.money0(fc.slice(1).reduce((s, x) => s + x.v, 0))} sub={L('Nov – Jan', 'nov. – janv.')} prov="e" onClick={() => calc(method)} />
        <Metric ic="coins" label={L('Operating profit, next 3 months', 'Profit d’exploitation, 3 mois')} value={fmt.money0(fc.slice(1).reduce((s, x) => s + x.v, 0) * (margin / 100))} sub={L('at', 'à') + ' ' + fmt.pct(margin) + ' ' + L('margin', 'de marge')} prov="e" onClick={() => calc({ ...method, title: L('Operating profit forecast', 'Prévision du profit'), value: fmt.money0(fc.slice(1).reduce((s, x) => s + x.v, 0) * (margin / 100)), formula: L('Forecast revenue × average operating margin of the last 3 months', 'Ventes prévues × marge moyenne des 3 derniers mois') })} />
      </section>
      <div className="panel">
        <div className="panel-head"><div><h3>{L('Revenue: actual and forecast', 'Ventes : réelles et prévues')}</h3><p className="muted">{L('Shaded band is the likely range', 'La bande ombrée est la fourchette probable')}</p></div><div className="legend"><span><i className="dot lc-sw lc-a"></i>{L('Actual', 'Réel')}</span><span><i className="dot lc-sw lc-warn"></i>{L('Forecast', 'Prévision')}</span></div></div>
        <LineChart labels={labels} series={[{ name: L('Actual', 'Réel'), values: act, tone: 'a' }, { name: L('Forecast', 'Prévision'), values: fcs, tone: 'warn', dash: 1 }]} band={{ lo, hi }} fmtv={(x, full) => (full ? fmt.money0(x) : fmt.kmoney(x))} height={230} every={1} />
      </div>
      <div className="panel panel-flush">
        <div className="table-scroll"><table className="table mtable"><thead><tr><th>{L('Month', 'Mois')}</th><th className="num">{L('Forecast', 'Prévision')}</th><th className="num hide-sm">{L('Likely range', 'Fourchette')}</th><th className="num hide-sm">{L('Last year', 'L’an dernier')}</th><th className="hide-md">{L('Based on', 'Basé sur')}</th></tr></thead>
          <tbody>{fc.map((x) => <tr key={x.l}><td className="cell-main">{x.l}</td><td className="num tnum">{fmt.money0(x.v)}</td><td className="num tnum hide-sm">{fmt.kmoney(x.v * (1 - x.w))} – {fmt.kmoney(x.v * (1 + x.w))}</td><td className="num tnum hide-sm">{fmt.money0(x.py)}</td><td className="muted hide-md">{x.base}</td></tr>)}</tbody></table></div>
      </div>
    </div>
  );
}

function FinBench() {
  const { L, lang, fmt, F, O, D, employees, calc } = useMizo();
  const m = monthsK()[11], full = (m.rev * 31) / 28;
  const shH = (s) => (s ? (s[1] - s[0] - (s[1] - s[0] > 300 ? 30 : 0)) / 60 : 0);
  const hrs = employees.reduce((t, e) => t + Object.values(e.sched).reduce((a, s) => a + shH(s), 0), 0) * 4;
  const ch = O.channels.reduce((s, c) => s + c.v, 0);
  const val = { food: m.foodPct, lab: m.labPct, prime: m.primePct, rent: (m.rent / m.rev) * 100, op: m.opPct, seat: full / D.restaurant.seats, splh: m.rev / hrs, deliv: ((O.channels[2].v + O.channels[3].v) / ch) * 100 };
  const fv = (b, x) => (b.unit === '$' ? fmt.money0(x) : fmt.pct(x));
  return (
    <div className="page">
      <PageHead sub={L('How Souvlaki Village compares with similar restaurants: 40–60 seat quick-service spots in Québec.', 'Comment Souvlaki Village se compare à des restaurants semblables : comptoirs de 40 à 60 places au Québec.')} />
      <div className="suggest"><Icon n="info" /><div>{L('These ranges are illustrative industry rules of thumb, not a live benchmark dataset. Your numbers are October to date.', 'Ces fourchettes sont des repères généraux de l’industrie, pas des données en direct. Vos chiffres : octobre à ce jour.')}</div></div>
      <div className="panel">
        {F.benchmarks.map((b) => { const x = val[b.k], span = b.hi - b.lo, mn = b.lo - span, mx = b.hi + span, pos = Math.min(100, Math.max(0, ((x - mn) / (mx - mn)) * 100)); const inR = x >= b.lo && x <= b.hi; const good = b.good === 'mid' ? inR : b.good === 'low' ? x <= b.hi : x >= b.lo; return (
          <button key={b.k} className="bench" onClick={() => calc({ title: b.name[lang], value: fv(b, x), prov: 'e', formula: L(`Typical range ${fv(b, b.lo)} – ${fv(b, b.hi)}`, `Fourchette typique ${fv(b, b.lo)} – ${fv(b, b.hi)}`), notes: [inR ? L('You are inside the typical range.', 'Vous êtes dans la fourchette typique.') : good ? L('You are doing better than the typical range.', 'Vous faites mieux que la fourchette.') : L('You are outside the typical range — worth a look.', 'Vous êtes hors de la fourchette — à examiner.')] })}>
            <span className="bench-n">{b.name[lang]}</span>
            <span className="bench-track"><span className="bench-band" style={{ left: '33.3%', width: '33.3%' }}></span><i className={'bench-pin ' + (good ? 'pos' : 'neg')} style={{ left: pos + '%' }}></i></span>
            <span className="bench-v tnum"><b className={good ? 'txt-pos' : 'txt-neg'}>{fv(b, x)}</b><span className="muted sm">{fv(b, b.lo)}–{fv(b, b.hi)}</span></span>
          </button>
        ); })}
      </div>
    </div>
  );
}

function FinLocations() {
  const { L, lang, fmt, F, toast, openAddLoc, locs } = useMizo();
  const m = F.months[11], s = 31 / 28;
  const parc = finK(fsum([{ ...m, rev: m.rev * s, fb: m.fb * s, pack: m.pack * s, lab: m.lab * s, util: m.util * s, other: m.other * s, days: 31 }]));
  const lv = F.locations[1];
  const laval = finK(fsum([{ rev: lv.rev, fb: lv.rev * (lv.fbPct / 100), pack: lv.rev * (lv.packPct / 100), lab: lv.rev * (lv.labPct / 100), rent: lv.rent, util: lv.util, other: lv.rev * (lv.otherPct / 100), days: 31 }]));
  const both = finK(fsum([{ ...parc }, { ...laval }].map((x) => ({ rev: x.rev, fb: x.fb, pack: x.pack, lab: x.lab, rent: x.rent, util: x.util, other: x.other, days: 31 }))));
  const cols = [[F.locations[0], parc, 'v'], [lv, laval, 'e']];
  const rows = [[L('Revenue / month', 'Ventes / mois'), (k) => fmt.money0(k.rev)], [L('Sales per seat', 'Ventes par place'), (k, l) => (l ? fmt.money0(k.rev / l.seats) : '—')], [L('Sales per sq. ft', 'Ventes par pi²'), (k, l) => (l ? fmt.money(k.rev / l.sqft) : '—')], [L('Food & beverage cost', 'Coût aliments et boissons'), (k) => fmt.pct((k.fb / k.rev) * 100)], [L('Labour', 'Main-d’œuvre'), (k) => fmt.pct(k.labPct)], [L('Prime cost', 'Coût principal'), (k) => fmt.pct(k.primePct)], [L('Rent', 'Loyer'), (k) => fmt.pct((k.rent / k.rev) * 100)], [L('Operating profit', 'Profit d’exploitation'), (k) => fmt.money0(k.op)], [L('Operating margin', 'Marge d’exploitation'), (k) => fmt.pct(k.opPct)]];
  return (
    <div className="page">
      <PageHead sub={L('Compare restaurants side by side. You have one open today — the second column is the Laval plan.', 'Comparez vos restaurants côte à côte. Un seul est ouvert — la 2ᵉ colonne est le projet de Laval.')} />
      <section className="loc-grid">
        {cols.map(([l, k, p]) => <div key={l.id} className="loc-card on" style={{ cursor: 'default' }}><span className="integ-ic"><Icon n={l.status === 'open' ? 'storefront' : 'map-pin'} s="1.3rem" /></span><span className="loc-name">{l.name}</span><span className="muted sm">{l.status === 'open' ? L('Open · October, projected to full month', 'Ouvert · octobre, projeté au mois complet') : l.opens[lang]} · {l.seats} {L('seats', 'places')}</span><span className="dr-row"><b className="tnum">{fmt.money0(k.rev)}</b><Prov k={p} /></span></div>)}
        {locs.map((l) => <div key={l.id} className="loc-card" style={{ cursor: 'default' }}><span className="integ-ic"><Icon n="map-pin" s="1.3rem" /></span><span className="loc-name">{l.name}</span><span className="muted sm">{l.opens[lang]} · {l.seats} {L('seats', 'places')} · {L('added this session', 'ajouté cette session')}</span><span className="dr-row"><span className="muted">{L('No projection yet', 'Pas encore de projection')}</span><Prov k="m" /></span></div>)}
        <button className="loc-card loc-add" onClick={openAddLoc}><span className="integ-ic"><Icon n="plus" s="1.3rem" /></span><span className="loc-name">{L('Add a location', 'Ajouter un restaurant')}</span><span className="muted sm">{L('Later phase', 'Phase ultérieure')}</span></button>
      </section>
      <div className="panel panel-flush">
        <div className="table-scroll">
          <table className="table mtable">
            <thead><tr><th></th>{cols.map(([l, , p]) => <th key={l.id} className="num">{l.name.split('— ')[1]} <Prov k={p} short /></th>)}<th className="num">{L('Combined', 'Combiné')} <Prov k="e" short /></th></tr></thead>
            <tbody>{rows.map(([n, f]) => <tr key={n}><td className="cell-main">{n}</td><td className="num tnum">{f(parc, cols[0][0])}</td><td className="num tnum">{f(laval, cols[1][0])}</td><td className="num tnum">{f(both, { seats: cols[0][0].seats + cols[1][0].seats, sqft: cols[0][0].sqft + cols[1][0].sqft })}</td></tr>)}</tbody>
          </table>
        </div>
      </div>
      <div className="suggest"><Icon n="info" /><div>{L('Laval is a pro forma: higher rent and a bigger room, with labour % helped by more seats. Every Laval number is a planning assumption, not a result.', 'Laval est un prévisionnel : loyer plus élevé, salle plus grande. Chaque chiffre de Laval est une hypothèse, pas un résultat.')}</div></div>
    </div>
  );
}

function Overview2() {
  const v = useFinView(); const { L, lang, fmt, F, D, P, md, calc, go, inv, recipes, invMap, insightState, fin } = v; const a = P.cur, b = P.cmp;
  const alerts = useAlerts();
  const [trend, setTrend] = React.useState('12m');
  const mk = monthsK();
  const invVal = inv.reduce((s, i) => s + i.onHand * i.cost, 0);
  const oct = F.days.filter((x) => x.d >= '2026-10-01');
  const tData = trend === '12m' ? F.months.map((m, i) => ({ label: m.label[lang], a: mk[i].rev, b: mk[i].rev - mk[i].op, m: mk[i].opPct })) : oct.slice(-14).map((x) => { const k = finK(fsum([x])); return { label: fmt.date(x.d, { day: 'numeric' }), a: k.rev, b: k.rev - k.op, m: k.opPct }; });
  const last7 = F.days.slice(-7).reverse();
  const byD = Object.fromEntries(F.days.map((x) => [x.d, x]));
  const wkAgo = (d) => { const t = new Date(d + 'T12:00'); t.setDate(t.getDate() - 7); return byD[t.toISOString().slice(0, 10)]; };
  const top = recipes.map((r) => ({ r, c: recipeCost(r, invMap) })).sort((x, y) => y.c.monthly - x.c.monthly).slice(0, 4);
  const intel = useIntel(), openIns = intel.open.slice().sort((x, y) => y.impact - x.impact).filter((x) => x.impact >= 1).slice(0, 4);
  const dayDrill = (x) => { const k = finK(fsum([x])), p = wkAgo(x.d); return { title: fmt.date(x.d, { weekday: 'long', month: 'long', day: 'numeric' }), value: fmt.money0(k.rev), prov: x.partial ? 'e' : 'v', provNote: x.partial ? L('Day not closed', 'Journée non fermée') : L('POS daily total', 'Total PDV'), formula: L('Revenue − cost of goods − labour − that day’s share of operating costs = operating profit', 'Ventes − marchandises − main-d’œuvre − part des frais du jour = profit d’exploitation'), inputs: [{ label: L('Revenue', 'Ventes'), v: fmt.money0(k.rev), prov: x.partial ? 'e' : 'v' }, { op: '−', label: L('Cost of goods (allocated)', 'Marchandises (répartition)'), v: fmt.money0(k.cogs), prov: 'e' }, { op: '−', label: L('Labour (time clock)', 'Main-d’œuvre (pointage)'), v: fmt.money0(k.lab), prov: 'e' }, { op: '−', label: L('Rent, utilities, fees (daily share)', 'Loyer, énergie, frais (part du jour)'), v: fmt.money0(k.opx), prov: 'e' }, { tot: true, op: '=', label: L('Operating profit (est.)', 'Profit d’exploitation (est.)'), v: fmt.money0(k.op) }, { label: L('Tickets · average', 'Additions · moyenne'), v: `${fmt.num(Math.round(k.tk))} · ${fmt.money(k.avgTk)}` }], cmp: p ? { lab: L('same day last week', 'même jour la semaine dernière'), v: fmt.money0(p.rev), delta: <Delta v={md(k.rev, p.rev)} /> } : null, notes: [L('Daily costs are allocated from monthly totals, so treat daily profit as a guide.', 'Les coûts quotidiens sont répartis des totaux mensuels : le profit quotidien est indicatif.')] }; };
  return (
    <div className="page">
      <PageHead sub={L("Here's how Souvlaki Village is doing — Wednesday, October 28.", 'Voici où en est Souvlaki Village — mercredi 28 octobre.')}><FinPicker /></PageHead>
      <SetupChecklist />
      <ProvLegend />
      <section className="kpis">
        <Metric hero ic="cash-register" label={L('Revenue', 'Ventes')} value={fmt.money0(a.rev)} delta={<Delta v={md(a.rev, b.rev)} />} cmpLab={P.cmpLab} prov={P.partial ? 'e' : 'v'} onClick={() => calc(finDrill('rev', v))} />
        <Metric ic="chart-pie-slice" label={L('Gross profit', 'Profit brut')} value={fmt.money0(a.gross)} delta={<Delta v={md(a.gross, b.gross)} />} sub={fmt.pct(a.grossPct)} prov={P.closed ? 'v' : 'e'} onClick={() => calc(finDrill('gross', v))} />
        <Metric ic="coins" label={L('Operating profit (est.)', 'Profit d’exploitation (est.)')} value={fmt.money0(a.op)} delta={<Delta v={md(a.op, b.op)} />} sub={fmt.pct(a.opPct)} prov="e" onClick={() => calc(finDrill('op', v))} />
        <Metric ic="package" label={L('Inventory value', 'Valeur de l’inventaire')} value={fmt.money0(invVal)} sub={inv.filter((i) => stockState(i) === 'low').length + ' ' + L('items low', 'articles bas')} prov="e" onClick={() => calc(finDrill('inv', v))} />
      </section>
      <section className="kpis">
        <Metric ic="bowl-food" label={L('Food cost', 'Coût alimentaire')} value={fmt.pct(a.foodPct)} delta={<Pts v={a.foodPct - b.foodPct} invert />} cmpLab={P.cmpLab} prov={P.closed ? 'v' : 'e'} onClick={() => calc(finDrill('food', v))} />
        <Metric ic="users-three" label={L('Labour', 'Main-d’œuvre')} value={fmt.pct(a.labPct)} delta={<Pts v={a.labPct - b.labPct} invert />} cmpLab={P.cmpLab} prov={P.closed ? 'v' : 'e'} onClick={() => calc(finDrill('lab', v))} />
        <Metric ic="scales" label={L('Prime cost', 'Coût principal')} value={fmt.pct(a.primePct)} delta={<Pts v={a.primePct - b.primePct} invert />} cmpLab={P.cmpLab} prov="e" onClick={() => calc(finDrill('prime', v))} />
        <Metric ic="receipt" label={L('Tickets', 'Additions')} value={fmt.num(Math.round(a.tk))} delta={<Delta v={md(a.tk, b.tk)} />} sub={L('avg', 'moy.') + ' ' + fmt.money(a.avgTk)} prov={P.partial ? 'e' : 'v'} onClick={() => calc(finDrill('rev', v))} />
      </section>
      <section className="grid-2-1">
        <div className="panel">
          <div className="panel-head"><div><h3>{L('Profitability trend', 'Tendance de rentabilité')}</h3><p className="muted">{L('Revenue vs. all operating costs · operating margin below', 'Ventes vs tous les coûts · marge d’exploitation en dessous')}</p></div><Seg size="sm" value={trend} onChange={setTrend} options={[['12m', L('12 months', '12 mois')], ['14d', L('14 days', '14 jours')]]} /></div>
          <BarChart data={tData} la={L('Revenue', 'Ventes')} lb={L('Costs', 'Coûts')} fmtv={(x, full) => (full ? fmt.money0(x) : fmt.kmoney(x))} height={230} highlightLast />
          <div className="margins">{tData.map((x, i) => <div key={i}><span className="muted sm">{x.label}</span><b className={'tnum ' + (x.m < 5 ? 'txt-warn' : '')}>{fmt.pct(x.m)}</b></div>)}</div>
        </div>
        <div className="panel">
          <div className="panel-head"><div><h3>{L('Needs your attention', 'À surveiller')}</h3><p className="muted">{alerts.length} {L('items across the restaurant', 'éléments dans le restaurant')}</p></div><button className="btn btn-ghost" onClick={() => go('overview', { tab: 'alerts' })}>{L('See all', 'Tout voir')}</button></div>
          <ul className="alerts">{alerts.slice(0, 6).map((x, i) => <li key={i} className="alert"><span className={'alert-ic ' + x.tone}><Icon n={x.ic} /></span><div className="alert-text"><div>{x.text}</div><div className="muted sm">{x.sub}</div></div><button className="btn btn-ghost" onClick={x.to}>{x.act}</button></li>)}</ul>
        </div>
      </section>
      <div className="panel panel-flush">
        <div className="panel-head pad"><div><h3>{L('Daily performance', 'Performance quotidienne')}</h3><p className="muted">{L('Last 7 days · click a day for its numbers', '7 derniers jours · cliquez sur un jour')}</p></div><button className="btn btn-ghost" onClick={() => go('finance', { tab: 'revenue' })}>{L('Revenue report', 'Rapport des ventes')}<Icon n="arrow-right" /></button></div>
        <div className="table-scroll">
          <table className="table mtable">
            <thead><tr><th>{L('Day', 'Jour')}</th><th className="num">{L('Sales', 'Ventes')}</th><th className="num hide-sm">{L('vs last week', 'vs sem. dern.')}</th><th className="num hide-sm">{L('Tickets', 'Additions')}</th><th className="num hide-md">{L('Avg ticket', 'Moyenne')}</th><th className="num">{L('Labour', 'Main-d’œuvre')}</th><th className="num">{L('Op. profit (est.)', 'Profit (est.)')}</th></tr></thead>
            <tbody>{last7.map((x) => { const k = finK(fsum([x])), p = wkAgo(x.d); return (
              <tr key={x.d} className="clickable" onClick={() => calc(dayDrill(x))}>
                <td><div className="cell-main">{fmt.date(x.d, { weekday: 'short', month: 'short', day: 'numeric' })}</div>{x.partial ? <div className="cell-sub">{L('so far · 2:20 pm', 'jusqu’ici · 14 h 20')}</div> : null}</td>
                <td className="num tnum">{fmt.money0(k.rev)}</td><td className="num hide-sm">{p && !x.partial ? <Delta v={md(k.rev, p.rev)} /> : <span className="muted">—</span>}</td><td className="num tnum hide-sm">{fmt.num(Math.round(k.tk))}</td><td className="num tnum hide-md">{fmt.money(k.avgTk)}</td>
                <td className="num"><Pill tone={k.labPct > 35 ? 'neg' : k.labPct > 31 ? 'warn' : 'pos'}>{fmt.pct(k.labPct)}</Pill></td><td className={'num tnum ' + (k.op < 0 ? 'txt-neg' : '')}>{fmt.money0(k.op)}</td>
              </tr>
            ); })}</tbody>
          </table>
        </div>
      </div>
      <section className="grid-1-1">
        <div className="panel ai-panel">
          <Meander />
          <div className="ai-kicker"><Icon n="drop-half-bottom" />{L('Profit leaks MIZO found', 'Fuites trouvées par MIZO')}</div>
          <h2 className="ai-headline">{L(`${fmt.money0(intel.openTotal)} a month you could keep`, `${fmt.money0(intel.openTotal)} par mois à récupérer`)}</h2>
          <ul className="ai-list">{openIns.map((i) => <li key={i.id}><span className="ai-amt">+{fmt.money0(i.impact)}</span><span>{i.title}</span></li>)}</ul>
          <button className="btn btn-primary" onClick={() => go('ai', { tab: 'leaks' })}>{L('Open the leak detector', 'Ouvrir le détecteur')}<Icon n="arrow-right" /></button>
        </div>
        <div className="panel">
          <div className="panel-head"><div><h3>{L('Most profitable dishes', 'Plats les plus rentables')}</h3><p className="muted">{L('Profit per month, after food cost only', 'Profit mensuel, après coût des aliments seulement')}</p></div></div>
          <HBars items={top.map(({ r, c }) => ({ label: r.name[lang], v: c.monthly, sub: L(`${fmt.num(r.sold)} sold · ${fmt.money(c.margin)} per plate`, `${fmt.num(r.sold)} vendus · ${fmt.money(c.margin)} par assiette`) }))} fmtv={fmt.money0} />
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { FinMenu, FinAP, FinForecast, FinBench, FinLocations, Overview2 });
