const shHrs = (s) => (s ? (s[1] - s[0] - (s[1] - s[0] > 300 ? 30 : 0)) / 60 : 0);
const EQ_EVERY = { fryer: 30, gyro: 42, linefridge: 90, walkin: 182, hood: 182, dish: 30, grill: 7 };

function Labour() {
  const { L, lang, fmt, O, employees, go } = useMizo();
  const sales = [O.dowRev[0], O.dowRev[1], O.dowRev[2], ...O.forecast.slice(0, 4).map((f) => f.rev)];
  const dayCost = (e, d) => { const s = e.sched[d]; if (!s) return 0; return e.type === 'salary' ? e.salary / (Object.keys(e.sched).length * 2) : shHrs(s) * e.rate; };
  const days = O.dow.map((n, d) => { const h = employees.reduce((a, e) => a + shHrs(e.sched[d]), 0), c = employees.reduce((a, e) => a + dayCost(e, d), 0); return { n, d, h, c, s: sales[d], p: (c / sales[d]) * 100, splh: sales[d] / h }; });
  const H = days.reduce((a, x) => a + x.h, 0), C = days.reduce((a, x) => a + x.c, 0), S = sales.reduce((a, x) => a + x, 0);
  const roles = Object.values(employees.reduce((m, e) => { const k = e.role[lang]; m[k] = m[k] || { label: k, v: 0, h: 0 }; Object.keys(e.sched).forEach((d) => { m[k].v += dayCost(e, Number(d)); m[k].h += shHrs(e.sched[d]); }); return m; }, {})).map((r) => ({ ...r, sub: `${fmt.num(Math.round(r.h))} h` })).sort((a, b) => b.v - a.v);
  const hrs = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23];
  const today = hrs.map((h) => { const m = h * 60 + 30; const on = employees.filter((e) => e.sched[2] && e.sched[2][0] <= m && e.sched[2][1] > m); const idx = O.hours.indexOf(h); return { label: h + 'h', a: idx >= 0 ? O.dowRev[2] * O.hourShape[idx] : 0, b: on.reduce((s, e) => s + (e.type === 'salary' ? 30 : e.rate), 0), n: on.length }; });
  return (
    <div className="page">
      <PageHead sub={L('What your schedule costs against what you expect to sell — by day, by role and by hour.', 'Ce que coûte l’horaire par rapport aux ventes prévues — par jour, poste et heure.')}>
        <button className="btn btn-secondary" onClick={() => go('team', { tab: 'schedule' })}><Icon n="calendar-blank" />{L('Edit schedule', 'Modifier l’horaire')}</button>
      </PageHead>
      <SeeAlso k="teamLabour" />
      <section className="stats">
        <Stat label={L('Labour this week', 'Main-d’œuvre cette semaine')} value={fmt.pct((C / S) * 100)} tone={(C / S) * 100 > 30 ? 'warn' : 'pos'}>{fmt.money0(C)} {L('on', 'pour')} {fmt.money0(S)} {L('in sales', 'de ventes')}</Stat>
        <Stat label={L('Sales per labour hour', 'Ventes par heure travaillée')} value={fmt.money0(S / H)}>{L('Aim for $65+', 'Visez 65 $ et plus')}</Stat>
        <Stat label={L('Scheduled hours', 'Heures prévues')} value={fmt.num(Math.round(H))}>{employees.length} {L('people', 'personnes')}</Stat>
        <Stat label={L('Most expensive day', 'Journée la plus chère')} value={days.slice().sort((a, b) => b.p - a.p)[0].n[lang]} tone="warn">{fmt.pct(days.slice().sort((a, b) => b.p - a.p)[0].p)} {L('of sales', 'des ventes')}</Stat>
      </section>
      <section className="grid-2-1">
        <div className="panel panel-flush">
          <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">{L('Hours', 'Heures')}</th><th className="num">{L('Labour', 'Coût')}</th><th className="num">%</th><th className="num hide-sm">{L('Sales / hour', 'Ventes / h')}</th></tr></thead>
              <tbody>{days.map((x) => <tr key={x.d}><td className="cell-main">{x.n[lang]}{x.d > 2 ? <div className="cell-sub">{L('forecast', 'prévision')}</div> : null}</td><td className="num tnum">{fmt.money0(x.s)}</td><td className="num tnum">{fmt.num(Math.round(x.h))}</td><td className="num tnum">{fmt.money0(x.c)}</td><td className="num"><Pill tone={x.p > 32 ? 'neg' : x.p > 28 ? 'warn' : 'pos'}>{fmt.pct(x.p)}</Pill></td><td className="num tnum hide-sm">{fmt.money0(x.splh)}</td></tr>)}</tbody>
            </table>
          </div>
        </div>
        <div className="panel"><div className="panel-head"><div><h3>{L('By role', 'Par poste')}</h3><p className="muted">{L('Wages this week', 'Salaires cette semaine')}</p></div></div><HBars items={roles} fmtv={fmt.money0} /></div>
      </section>
      <div className="panel">
        <div className="panel-head"><div><h3>{L('Today, hour by hour', 'Aujourd’hui, heure par heure')}</h3><p className="muted">{L('Average Wednesday sales vs. what the people on shift cost per hour', 'Ventes moyennes du mercredi vs coût horaire de l’équipe en poste')}</p></div><div className="legend"><span><i className="dot dot-a"></i>{L('Sales', 'Ventes')}</span><span><i className="dot dot-b"></i>{L('Labour', 'Main-d’œuvre')}</span></div></div>
        <BarChart data={today} la={L('Sales', 'Ventes')} lb={L('Labour', 'Main-d’œuvre')} fmtv={(v, full) => (full ? fmt.money0(v) : fmt.kmoney(v))} height={180} />
        <div className="suggest"><Icon n="sparkle" /><div>{L('3 pm – 5 pm carries 6 people for about $280 in sales. Starting one line cook at 5 pm instead of 3 pm saves about $40 a day.', 'De 15 h à 17 h, 6 personnes pour environ 280 $ de ventes. Faire commencer un cuisinier à 17 h plutôt qu’à 15 h économise environ 40 $ par jour.')}</div></div>
      </div>
    </div>
  );
}

function StaffTasks() {
  const { L, lang, fmt, employees, ops, upd, toast } = useMizo();
  const [f, setF] = React.useState('open');
  const [who, setWho] = React.useState('all');
  const [add, setAdd] = React.useState(null);
  const first = (id) => (employees.find((e) => e.id === id) || { name: id === 'eleni' ? 'Eleni Papadakis' : id }).name.split(' ')[0];
  const people = [['eleni', 'Eleni'], ...employees.map((e) => [e.id, e.name.split(' ')[0]])];
  const rows = ops.tasks.filter((t) => (f === 'all' || (f === 'open' ? !t.done : t.done)) && (who === 'all' || t.who === who)).sort((a, b) => a.due.localeCompare(b.due));
  const pri = { high: [L('High', 'Haute'), 'neg'], med: [L('Normal', 'Normale'), 'neutral'], low: [L('Low', 'Basse'), 'neutral'] };
  return (
    <div className="page">
      <PageHead sub={L('One-off jobs outside the daily checklists — who’s on it and when it’s due.', 'Tâches ponctuelles hors des listes quotidiennes — qui s’en occupe et pour quand.')}>
        <button className="btn btn-primary" onClick={() => setAdd({ title: '', who: 'nikos', due: TODAY, pri: 'med' })}><Icon n="plus" />{L('New task', 'Nouvelle tâche')}</button>
      </PageHead>
      <section className="stats">
        <Stat label={L('Open', 'Ouvertes')} value={ops.tasks.filter((t) => !t.done).length}>{L('Across the team', 'Pour l’équipe')}</Stat>
        <Stat label={L('Overdue', 'En retard')} value={ops.tasks.filter((t) => !t.done && t.due < TODAY).length} tone="neg" />
        <Stat label={L('Due today', 'Pour aujourd’hui')} value={ops.tasks.filter((t) => !t.done && t.due === TODAY).length} tone="warn" />
      </section>
      <div className="panel panel-flush">
        <div className="toolbar"><Seg size="sm" value={f} onChange={setF} options={[['open', L('Open', 'Ouvertes')], ['done', L('Done', 'Faites')], ['all', L('All', 'Toutes')]]} /><select className="input" style={{ maxWidth: 200 }} value={who} onChange={(e) => setWho(e.target.value)}><option value="all">{L('Everyone', 'Tout le monde')}</option>{people.map(([id, n]) => <option key={id} value={id}>{n}</option>)}</select></div>
        <ul className="cl task-list">{rows.map((t) => (
          <li key={t.id}><label className={'check' + (t.done ? ' done' : '')}><input type="checkbox" checked={t.done} onChange={() => { upd('tasks', (ts) => ts.map((x) => (x.id === t.id ? { ...x, done: !x.done } : x))); if (!t.done) toast(L('Task done', 'Tâche faite')); }} /><span>{t.title[lang]}</span></label>
            <span className="task-meta">{t.pri === 'high' ? <Pill tone="neg">{pri.high[0]}</Pill> : null}<span className="muted sm">{first(t.who)}</span><Pill tone={!t.done && t.due < TODAY ? 'neg' : !t.done && t.due === TODAY ? 'warn' : 'neutral'}>{t.due === TODAY ? L('Today', 'Aujourd’hui') : fmt.date(t.due, { weekday: 'short', month: 'short', day: 'numeric' })}</Pill></span></li>
        ))}{!rows.length ? <li className="empty">{L('No tasks here.', 'Aucune tâche.')}</li> : null}</ul>
      </div>
      <Modal open={!!add} onClose={() => setAdd(null)} title={L('New task', 'Nouvelle tâche')} actions={<><button className="btn btn-secondary" onClick={() => setAdd(null)}>{L('Cancel', 'Annuler')}</button><button className="btn btn-primary" disabled={!add || !add.title.trim()} onClick={() => { upd('tasks', (ts) => [{ id: 'k' + Date.now(), title: { en: add.title, fr: add.title }, who: add.who, due: add.due, pri: add.pri, done: false }, ...ts]); toast(L(`Assigned to ${first(add.who)}`, `Assignée à ${first(add.who)}`)); setAdd(null); }}>{L('Add task', 'Ajouter')}</button></>}>
        {add ? <div className="form-grid">
          <div className="field span-2"><label>{L('What needs doing?', 'Quoi faire?')}</label><input className="input" autoFocus value={add.title} onChange={(e) => setAdd({ ...add, title: e.target.value })} /></div>
          <div className="field"><label>{L('Who', 'Qui')}</label><select className="input" value={add.who} onChange={(e) => setAdd({ ...add, who: e.target.value })}>{people.map(([id, n]) => <option key={id} value={id}>{n}</option>)}</select></div>
          <div className="field"><label>{L('Due', 'Échéance')}</label><input className="input" type="date" value={add.due} onChange={(e) => setAdd({ ...add, due: e.target.value })} /></div>
          <div className="field span-2"><label>{L('Priority', 'Priorité')}</label><Seg size="sm" value={add.pri} onChange={(v) => setAdd({ ...add, pri: v })} options={Object.entries(pri).map(([k, v]) => [k, v[0]])} /></div>
        </div> : null}
      </Modal>
    </div>
  );
}

function FoodSafety() {
  const { L, lang, fmt, O, employees, ops, upd, go, toast } = useMizo();
  const [six, setSix] = React.useState('');
  const [ppm, setPpm] = React.useState('');
  const first = (id) => employees.find((e) => e.id === id).name;
  const units = [['walkin', O.temps[0]], ['line', O.temps[1]], ['freezer', O.temps[2]], ['hot', O.temps[3]]];
  const bad = (t, v) => (t.hot ? v < t.lim : v > t.lim);
  const days = ['Thu', 'Fri', 'Sat', 'Sun', 'Mon', 'Tue', 'Wed'].map((d, i) => (lang === 'fr' ? ['jeu', 'ven', 'sam', 'dim', 'lun', 'mar', 'mer'][i] : d));
  const coolOk = (c) => c.two && c.two[0] <= 21 && (!c.six || c.six[0] <= 4);
  return (
    <div className="page">
      <PageHead sub={L('Temperatures, cooling, sanitizer and certificates — the records a MAPAQ inspector asks to see.', 'Températures, refroidissement, assainisseur et certificats — ce que l’inspecteur du MAPAQ demande.')} />
      <section className="stats">
        <Stat label={L('Out of range today', 'Hors limite aujourd’hui')} value={O.temps.filter((t) => bad(t, t.v)).length} tone="neg">{L('Line fridge', 'Frigo de ligne')}</Stat>
        <Stat label={L('Cooling logs open', 'Refroidissements en cours')} value={ops.cooling.filter((c) => !c.six).length} tone="warn">{L('6-hour reading due', 'Lecture de 6 h due')}</Stat>
        <Stat label={L('Certificates expiring', 'Certificats à renouveler')} value={O.certs.filter((c) => daysTo(c.exp) < 60).length} tone="warn">{L('Within 60 days', 'D’ici 60 jours')}</Stat>
        <Stat label={L('Last pest control', 'Dernier contrôle parasitaire')} value={fmt.date(O.pest[0].date)} tone="pos">{O.pest[0].vendor}</Stat>
      </section>
      <div className="panel panel-flush">
        <div className="panel-head pad"><div><h3>{L('Temperature history', 'Historique des températures')}</h3><p className="muted">{L('Morning readings, last 7 days · today’s readings are logged in Checklists', 'Lectures du matin, 7 derniers jours · les lectures du jour se font dans Listes de tâches')}</p></div><button className="btn btn-secondary" onClick={() => go('team', { tab: 'tasks' })}>{L('Log a reading', 'Noter une lecture')}</button></div>
        <div className="table-scroll">
          <table className="table mtable perm">
            <thead><tr><th>{L('Unit', 'Appareil')}</th>{days.map((d) => <th key={d} className="num">{d}</th>)}<th className="num">{L('Limit', 'Limite')}</th></tr></thead>
            <tbody>{units.map(([k, t]) => <tr key={k}><td className="cell-main">{t.name[lang]}</td>{O.tempHist[k].map((v, i) => <td key={i} className={'num tnum ' + (bad(t, v) ? 'txt-neg' : '')}>{fmt.num(v)}°</td>)}<td className="num tnum muted">{t.hot ? '≥' : '≤'} {t.lim}°</td></tr>)}</tbody>
          </table>
        </div>
        <div className="toolbar"><div className="suggest warnbox" style={{ flex: 1 }}><Icon n="trend-up" /><div>{L('The line fridge has crept up every day this week. That usually means a door gasket or condenser coil — not a one-off.', 'Le frigo de ligne monte chaque jour cette semaine. Souvent un joint de porte ou un serpentin encrassé.')}</div><button className="btn btn-secondary" onClick={() => go('team', { tab: 'equipment' })}>{L('Equipment', 'Équipement')}</button></div></div>
      </div>
      <section className="grid-1-1">
        <div className="panel panel-flush">
          <div className="panel-head pad"><div><h3>{L('Cooling log', 'Registre de refroidissement')}</h3><p className="muted">{L('Cooked food must reach 21 °C within 2 h and 4 °C within 6 h', 'Les aliments cuits doivent atteindre 21 °C en 2 h et 4 °C en 6 h')}</p></div></div>
          <div className="table-scroll">
            <table className="table mtable">
              <thead><tr><th>{L('Item', 'Aliment')}</th><th className="num">{L('Start', 'Départ')}</th><th className="num">2 h</th><th className="num">6 h</th><th></th></tr></thead>
              <tbody>{ops.cooling.map((c, i) => (
                <tr key={i}><td><div className="cell-main">{c.item[lang]}</div><div className="cell-sub">{fmt.date(c.date)} · {c.by}</div></td><td className="num tnum">{c.start[0]}°<div className="cell-sub">{c.start[1]}</div></td><td className={'num tnum ' + (c.two[0] > 21 ? 'txt-neg' : '')}>{c.two[0]}°<div className="cell-sub">{c.two[1]}</div></td>
                  <td className="num">{c.six ? <span className={'tnum ' + (c.six[0] > 4 ? 'txt-neg' : '')}>{c.six[0]}°<div className="cell-sub">{c.six[1]}</div></span> : <div className="portion" style={{ justifyContent: 'flex-end' }}><input className="input" type="number" placeholder="°C" value={six} onChange={(e) => setSix(e.target.value)} /><button className="btn btn-secondary" disabled={six === ''} onClick={() => { upd('cooling', (cs) => cs.map((x, j) => (j === i ? { ...x, six: [Number(six), '20:05'] } : x))); setSix(''); toast(L('6-hour reading logged', 'Lecture de 6 h notée')); }}>{L('Log', 'Noter')}</button></div>}</td>
                  <td>{!c.six ? <Pill tone="warn">{L('Open', 'En cours')}</Pill> : coolOk(c) ? <Pill tone="pos">OK</Pill> : <Pill tone="neg">{L('Failed', 'Échoué')}</Pill>}</td></tr>
              ))}</tbody>
            </table>
          </div>
        </div>
        <div className="panel">
          <h3>{L('Sanitizer checks today', 'Vérifications d’assainisseur')}</h3>
          {ops.sanitizer.map((s, i) => <div key={i} className="ln"><span>{s.t} · {s.where[lang]} · {s.by}</span><b className={s.ppm < 150 || s.ppm > 400 ? 'txt-neg' : 'txt-pos'}>{s.ppm} ppm</b></div>)}
          <div className="portion"><input className="input" type="number" placeholder="ppm" value={ppm} onChange={(e) => setPpm(e.target.value)} style={{ width: '7rem' }} /><button className="btn btn-secondary" disabled={!ppm} onClick={() => { upd('sanitizer', (ss) => [{ t: '14:20', where: { en: 'Line buckets', fr: 'Seaux de ligne' }, ppm: Number(ppm), by: 'Eleni' }, ...ss]); setPpm(''); }}>{L('Log check', 'Noter')}</button><span className="muted sm">{L('Quat: 150–400 ppm', 'Quat : 150–400 ppm')}</span></div>
          <h3 style={{ marginTop: '.6rem' }}>{L('Pest control', 'Contrôle parasitaire')}</h3>
          {O.pest.map((p, i) => <div key={i} className="ln"><span>{fmt.date(p.date)} · {p.vendor}</span><span className="muted sm">{p.result[lang]}</span></div>)}
        </div>
      </section>
      <div className="panel panel-flush">
        <div className="panel-head pad"><h3>{L('Food safety certificates', 'Certificats d’hygiène')}</h3></div>
        <div className="table-scroll">
          <table className="table mtable">
            <thead><tr><th>{L('Person', 'Personne')}</th><th>{L('Certificate', 'Certificat')}</th><th>{L('Expires', 'Expire')}</th></tr></thead>
            <tbody>{O.certs.map((c) => { const d = daysTo(c.exp); return <tr key={c.who}><td className="cell-main">{first(c.who)}</td><td>{c.cert[lang]}</td><td><Pill tone={d < 60 ? 'warn' : 'pos'}>{fmt.date(c.exp, { year: 'numeric', month: 'short', day: 'numeric' })}</Pill></td></tr>; })}</tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

function Equipment() {
  const { L, lang, fmt, O, ops, upd, toast } = useMizo();
  const [sel, setSel] = React.useState(null);
  const [svc, setSvc] = React.useState({ what: '', by: '', cost: '' });
  const [prob, setProb] = React.useState('');
  const e = ops.equip.find((x) => x.id === sel);
  const st = { ok: [L('Working', 'Fonctionne'), 'pos'], due: [L('Service due', 'Entretien dû'), 'warn'], issue: [L('Problem', 'Problème'), 'neg'] };
  const where = { line: L('Kitchen line', 'Ligne'), walkin: L('Walk-in', 'Chambre froide'), dish: L('Dish pit', 'Plonge') };
  const logSvc = () => { upd('equip', (es) => es.map((x) => (x.id === e.id ? { ...x, last: TODAY, next: addDays(TODAY, EQ_EVERY[x.id] || 30), status: 'ok', issue: null } : x))); upd('equipLog', (l) => [{ date: TODAY, eq: e.id, what: { en: svc.what, fr: svc.what }, by: svc.by || 'Eleni', cost: Number(svc.cost) || 0 }, ...l]); setSvc({ what: '', by: '', cost: '' }); toast(L('Service logged · next date updated', 'Entretien noté · prochaine date mise à jour')); };
  const report = () => { upd('equip', (es) => es.map((x) => (x.id === e.id ? { ...x, status: 'issue', issue: { en: prob, fr: prob } } : x))); upd('tasks', (ts) => [{ id: 'k' + Date.now(), title: { en: `Fix: ${e.name.en} — ${prob}`, fr: `Réparer : ${e.name.fr} — ${prob}` }, who: 'nikos', due: TODAY, pri: 'high', done: false }, ...ts]); setProb(''); toast(L('Problem reported · task created for Nikos', 'Problème signalé · tâche créée pour Nikos')); };
  return (
    <div className="page">
      <PageHead sub={L('Every machine in the kitchen, when it was last serviced and what’s coming up.', 'Chaque appareil de la cuisine, son dernier entretien et ce qui s’en vient.')} />
      <section className="stats">
        <Stat label={L('Problems', 'Problèmes')} value={ops.equip.filter((x) => x.status === 'issue').length} tone="neg" />
        <Stat label={L('Service due', 'Entretiens dus')} value={ops.equip.filter((x) => daysTo(x.next) <= 3).length} tone="warn">{L('Next 3 days', '3 prochains jours')}</Stat>
        <Stat label={L('Maintenance spend', 'Coût d’entretien')} value={fmt.money0(ops.equipLog.reduce((s, l) => s + l.cost, 0))}>{L('Last 60 days', '60 derniers jours')}</Stat>
      </section>
      <div className="panel panel-flush">
        <div className="table-scroll">
          <table className="table mtable">
            <thead><tr><th>{L('Equipment', 'Équipement')}</th><th className="hide-sm">{L('Where', 'Où')}</th><th className="hide-md">{L('Schedule', 'Fréquence')}</th><th>{L('Next service', 'Prochain entretien')}</th><th>{L('Status', 'État')}</th></tr></thead>
            <tbody>{ops.equip.map((x) => { const d = daysTo(x.next); return (
              <tr key={x.id} className="clickable" onClick={() => setSel(x.id)}><td><div className="cell-main">{x.name[lang]}</div><div className="cell-sub">{typeof x.model === 'string' ? x.model : x.model[lang]}{x.issue ? ' · ' + x.issue[lang] : ''}</div></td><td className="hide-sm">{where[x.loc]}</td><td className="hide-md">{x.every[lang]}</td>
                <td className="tnum"><span className={d < 0 ? 'txt-neg' : d <= 3 ? 'txt-warn' : ''}>{fmt.date(x.next, { weekday: 'short', month: 'short', day: 'numeric' })}</span></td><td><Pill tone={st[x.status][1]}>{st[x.status][0]}</Pill></td></tr>
            ); })}</tbody>
          </table>
        </div>
      </div>
      <Drawer open={!!e} onClose={() => setSel(null)}>
        {e ? (
          <div className="dr">
            <div className="dr-head"><div><div className="card-kicker">{where[e.loc]}</div><h2>{e.name[lang]}</h2></div><button className="btn btn-icon btn-secondary" onClick={() => setSel(null)} aria-label="Close"><Icon n="x" /></button></div>
            <div className="dr-sec">
              <div className="dr-row"><span className="muted">{L('Model', 'Modèle')}</span><b>{typeof e.model === 'string' ? e.model : e.model[lang]}</b></div>
              <div className="dr-row"><span className="muted">{L('Last service', 'Dernier entretien')}</span><b>{fmt.date(e.last, { year: 'numeric', month: 'short', day: 'numeric' })}</b></div>
              <div className="dr-row"><span className="muted">{L('Next service', 'Prochain')}</span><b>{fmt.date(e.next, { year: 'numeric', month: 'short', day: 'numeric' })}</b></div>
              {e.issue ? <div className="suggest warnbox"><Icon n="warning" /><div>{e.issue[lang]}</div></div> : null}
            </div>
            <div className="dr-sec">
              <div className="dr-label">{L('Log a service', 'Noter un entretien')}</div>
              <input className="input" placeholder={L('What was done', 'Ce qui a été fait')} value={svc.what} onChange={(ev) => setSvc({ ...svc, what: ev.target.value })} />
              <div className="form-grid"><input className="input" placeholder={L('By (person or company)', 'Par (personne ou entreprise)')} value={svc.by} onChange={(ev) => setSvc({ ...svc, by: ev.target.value })} /><input className="input" type="number" placeholder={L('Cost (CAD)', 'Coût (CAD)')} value={svc.cost} onChange={(ev) => setSvc({ ...svc, cost: ev.target.value })} /></div>
              <button className="btn btn-primary" disabled={!svc.what.trim()} onClick={logSvc}><Icon n="wrench" />{L('Save service', 'Enregistrer')}</button>
            </div>
            <div className="dr-sec">
              <div className="dr-label">{L('Report a problem', 'Signaler un problème')}</div>
              <div className="ask-row"><input className="input" placeholder={L('e.g. Not holding temperature', 'ex. Ne garde pas la température')} value={prob} onChange={(ev) => setProb(ev.target.value)} /><button className="btn btn-secondary" disabled={!prob.trim()} onClick={report}>{L('Report', 'Signaler')}</button></div>
            </div>
            <div className="dr-sec">
              <div className="dr-label">{L('Service history', 'Historique')}</div>
              {ops.equipLog.filter((l) => l.eq === e.id).map((l, i) => <div key={i} className="ln"><span>{fmt.date(l.date)} · {l.what[lang]} · {l.by}</span><b>{l.cost ? fmt.money(l.cost) : '—'}</b></div>)}
              {!ops.equipLog.some((l) => l.eq === e.id) ? <span className="muted sm">{L('No service logged yet.', 'Aucun entretien noté.')}</span> : null}
            </div>
          </div>
        ) : null}
      </Drawer>
    </div>
  );
}

function ManagerLog() {
  const { L, lang, fmt, O, ops, upd, toast } = useMizo();
  const tagsL = { '86': L('86’d item', 'Rupture'), staff: L('Staffing', 'Personnel'), guest: L('Guest', 'Client'), equip: L('Equipment', 'Équipement'), incident: L('Incident', 'Incident'), delivery: L('Delivery', 'Livraison') };
  const blank = { shift: 'lunch', sales: '', tags: [], text: '', follow: '' };
  const [f, setF] = React.useState(blank);
  const [tag, setTag] = React.useState('all');
  const save = () => { upd('notes', (n) => [{ id: 'n' + Date.now(), date: TODAY, shift: f.shift, by: 'Eleni', sales: Number(f.sales) || null, tags: f.tags, text: { en: f.text, fr: f.text }, follow: f.follow ? { en: f.follow, fr: f.follow } : null }, ...n]); setF(blank); toast(L('Note saved to the log', 'Note ajoutée au journal')); };
  const toTask = (n) => { upd('tasks', (ts) => [{ id: 'k' + Date.now(), title: n.follow, who: 'nikos', due: addDays(n.date, 2), pri: 'med', done: false }, ...ts]); upd('notes', (ns) => ns.map((x) => (x.id === n.id ? { ...x, tasked: true } : x))); toast(L('Task created for Nikos', 'Tâche créée pour Nikos')); };
  const list = ops.notes.filter((n) => tag === 'all' || n.tags.includes(tag));
  return (
    <div className="page">
      <PageHead sub={L('What happened on each shift, in the manager’s words — so the next person walks in knowing.', 'Ce qui s’est passé à chaque quart, dans les mots du gérant — pour que le suivant soit au courant.')} />
      <section className="grid-1-2">
        <div className="panel">
          <h3>{L('Today’s note', 'Note du jour')}</h3>
          <div className="form-grid">
            <div className="field"><label>{L('Shift', 'Quart')}</label><Seg size="sm" value={f.shift} onChange={(v) => setF({ ...f, shift: v })} options={[['lunch', L('Lunch', 'Dîner')], ['dinner', L('Dinner', 'Souper')]]} /></div>
            <div className="field"><label>{L('Shift sales (CAD)', 'Ventes du quart (CAD)')}</label><input className="input" type="number" value={f.sales} onChange={(e) => setF({ ...f, sales: e.target.value })} /></div>
          </div>
          <div className="chips">{Object.entries(tagsL).map(([k, n]) => <button key={k} className={'chip' + (f.tags.includes(k) ? ' on' : '')} aria-pressed={f.tags.includes(k)} onClick={() => setF({ ...f, tags: f.tags.includes(k) ? f.tags.filter((x) => x !== k) : [...f.tags, k] })}>{n}</button>)}</div>
          <div className="field"><label>{L('What happened', 'Ce qui s’est passé')}</label><textarea className="input" rows="4" value={f.text} onChange={(e) => setF({ ...f, text: e.target.value })} placeholder={L('Rushes, run-outs, staff, guests, anything odd…', 'Coups de feu, ruptures, personnel, clients, imprévus…')}></textarea></div>
          <div className="field"><label>{L('Follow-up needed (optional)', 'Suivi requis (facultatif)')}</label><input className="input" value={f.follow} onChange={(e) => setF({ ...f, follow: e.target.value })} /></div>
          <button className="btn btn-primary" disabled={!f.text.trim()} onClick={save} style={{ alignSelf: 'flex-start' }}><Icon n="note-pencil" />{L('Save note', 'Enregistrer')}</button>
        </div>
        <div className="sec">
          <Seg size="sm" value={tag} onChange={setTag} options={[['all', L('All', 'Tout')], ...Object.entries(tagsL)]} />
          {list.map((n) => (
            <article key={n.id} className="panel">
              <div className="panel-head"><div><div className="card-kicker">{fmt.date(n.date, { weekday: 'long', month: 'short', day: 'numeric' })} · {n.shift === 'lunch' ? L('Lunch', 'Dîner') : L('Dinner', 'Souper')}</div><h4>{n.by}</h4></div>{n.sales ? <span className="tnum muted">{fmt.money0(n.sales)}</span> : null}</div>
              <p style={{ margin: 0 }}>{n.text[lang]}</p>
              {n.tags.length ? <div className="tagrow">{n.tags.map((t) => <span key={t} className="tag tag-neutral">{tagsL[t]}</span>)}</div> : null}
              {n.follow ? <div className="dr-row"><span className="muted sm"><Icon n="arrow-bend-down-right" /> {n.follow[lang]}</span>{n.tasked ? <Pill tone="pos">{L('Task created', 'Tâche créée')}</Pill> : <button className="btn btn-ghost" onClick={() => toTask(n)}>{L('Make it a task', 'Créer une tâche')}</button>}</div> : null}
            </article>
          ))}
        </div>
      </section>
    </div>
  );
}

Object.assign(window, { Labour, StaffTasks, FoodSafety, Equipment, ManagerLog });
