const SECTIONS = [
  { id: 'overview', ic: 'squares-four', s: ['Overview', 'Accueil'], t: ['Overview', 'Accueil'], tabs: [['dashboard', 'Dashboard', 'Tableau de bord'], ['alerts', 'Alerts', 'Alertes'], ['activity', 'Activity', 'Activité']] },
  { id: 'inventory', ic: 'package', s: ['Inventory', 'Inventaire'], t: ['Inventory', 'Inventaire'], tabs: [['stock', 'Stock levels', 'Niveaux de stock'], ['ingredients', 'Ingredients', 'Ingrédients'], ['counts', 'Counts', 'Comptages'], ['locations', 'Locations & transfers', 'Lieux et transferts'], ['expiry', 'Expiry', 'Dates de péremption'], ['waste', 'Waste', 'Pertes'], ['variance', 'Used vs expected', 'Utilisé vs prévu'], ['movements', 'Stock history', 'Historique du stock'], ['reorder', 'Reorder', 'Réapprovisionnement']] },
  { id: 'menu', ic: 'cooking-pot', s: ['Menu', 'Menu'], t: ['Menu & Recipes', 'Menu et recettes'], tabs: [['recipes', 'Recipe builder', 'Recettes et coûts'], ['prep', 'Prep & sub-recipes', 'Préparations'], ['yields', 'Yields', 'Rendements'], ['subs', 'Substitutions', 'Substitutions'], ['allergens', 'Allergens', 'Allergènes'], ['engineering', 'Menu engineering', 'Ingénierie du menu'], ['sim', 'Price simulator', 'Simulateur de prix'], ['pricing', 'Channel pricing', 'Prix par canal']] },
  { id: 'purchasing', ic: 'truck', s: ['Purchasing', 'Achats'], t: ['Purchasing & Suppliers', 'Achats et fournisseurs'], tabs: [['orders', 'Purchase orders', 'Bons de commande'], ['approvals', 'Approvals', 'Approbations'], ['receiving', 'Receiving', 'Réception'], ['returns', 'Returns & credits', 'Retours et crédits'], ['invoices', 'Invoices', 'Factures'], ['scan', 'Invoice scanning', 'Lecture de factures'], ['suppliers', 'Suppliers', 'Fournisseurs'], ['prices', 'Compare prices', 'Comparer les prix']] },
  { id: 'sales', ic: 'cash-register', s: ['Sales', 'Ventes'], t: ['Sales & POS', 'Ventes et point de vente'], tabs: [['summary', 'Summary', 'Sommaire'], ['mix', 'Items & categories', 'Articles et catégories'], ['channels', 'Channels', 'Canaux'], ['delivery', 'Delivery apps', 'Applis de livraison'], ['tickets', 'Transactions', 'Transactions'], ['payments', 'Refunds & discounts', 'Remboursements et rabais'], ['recon', 'Reconciliation', 'Rapprochement'], ['pos', 'POS setup', 'Configuration PDV']] },
  { id: 'team', ic: 'users-three', s: ['Team', 'Équipe'], t: ['Team & Operations', 'Équipe et opérations'], tabs: [['schedule', 'Schedule', 'Horaire'], ['clock', 'Time clock', 'Pointage'], ['sheets', 'Timesheets', 'Feuilles de temps'], ['run', 'Payroll', 'Paie'], ['team', 'Staff', 'Personnel'], ['labour', 'Labour cost', 'Coût de main-d’œuvre'], ['tasks', 'Checklists', 'Listes de vérification'], ['todo', 'Tasks', 'Tâches'], ['safety', 'Food safety', 'Salubrité'], ['equipment', 'Equipment', 'Équipement'], ['log', 'Manager log', 'Journal du gérant']] },
  { id: 'finance', ic: 'chart-line-up', s: ['Finance', 'Finances'], t: ['Financial Intelligence', 'Intelligence financière'], tabs: [['summary', 'Summary', 'Sommaire'], ['pnl', 'Profit & loss', 'État des résultats'], ['revenue', 'Revenue', 'Ventes'], ['costs', 'Costs & margins', 'Coûts et marges'], ['foodbev', 'Food & beverage cost', 'Coût aliments et boissons'], ['labour', 'Labour', 'Main-d’œuvre'], ['prime', 'Prime cost', 'Coût principal'], ['inventory', 'Inventory & waste', 'Inventaire et pertes'], ['suppliers', 'Supplier costs', 'Coûts fournisseurs'], ['menu', 'Menu profitability', 'Rentabilité du menu'], ['cash', 'Cash flow', 'Trésorerie'], ['ap', 'Bills to pay', 'Factures à payer'], ['budget', 'Budget vs actual', 'Budget vs réel'], ['forecast', 'Forecast', 'Prévisions'], ['bench', 'Compare to others', 'Comparer aux autres'], ['locations', 'Locations', 'Restaurants']] },
  { id: 'ai', ic: 'sparkle', s: ['Intelligence', 'Intelligence'], t: ['MIZO Intelligence', 'MIZO Intelligence'], tabs: [['ask', 'Assistant', 'Assistant'], ['leaks', 'Profit leaks', 'Fuites de profit'], ['suggestions', 'Recommendations', 'Recommandations'], ['health', 'Health score', 'Score santé'], ['simulate', 'Simulator', 'Simulateur'], ['briefings', 'Briefings', 'Résumés'], ['buying', 'Smart ordering', 'Commande intelligente'], ['forecast', 'Forecasts', 'Prévisions'], ['automations', 'Automations', 'Automatisations']] },
  { id: 'settings', ic: 'gear-six', s: ['Settings', 'Réglages'], t: ['Settings', 'Paramètres'], tabs: [['general', 'General', 'Général'], ['users', 'Users & roles', 'Utilisateurs et rôles'], ['integrations', 'Connections', 'Connexions'], ['notifications', 'Notifications', 'Notifications']] },
];
// legacy page ids → [section, default subtab]
const SECTION_ALIAS = { suppliers: ['purchasing', 'suppliers'], recipes: ['menu', 'recipes'], payroll: ['team', 'run'], insights: ['ai', 'suggestions'] };

function SectionHead({ sec, tab, setTab, title, counts }) {
  const { L } = useMizo();
  const nav = React.useRef(null);
  React.useEffect(() => { const n = nav.current; if (!n || n.scrollWidth <= n.clientWidth) return; const b = n.querySelector('.subnav-btn.on'); if (b) n.scrollTo({ left: Math.max(0, b.offsetLeft - 16) }); }, [tab, sec.id]);
  return (
    <header className="sec-head">
      <h1>{title || L(...sec.t)}</h1>
      <nav ref={nav} className="subnav" role="tablist" aria-label={L(...sec.t)}>
        {sec.tabs.map(([id, en, fr]) => (
          <button key={id} role="tab" aria-selected={tab === id} className={'subnav-btn' + (tab === id ? ' on' : '')} onClick={() => setTab(id)}>
            {L(en, fr)}{counts && counts[id] ? <span className="cnt">{counts[id]}</span> : null}
          </button>
        ))}
      </nav>
    </header>
  );
}

function useAlerts() {
  const { L, lang, fmt, D, O, inv, invoices, punches, employees, P, now, recipes, invMap, target, go, pos } = useMizo();
  const sup = (id) => D.suppliers.find((s) => s.id === id).name;
  const first = (id) => employees.find((e) => e.id === id).name.split(' ')[0];
  const a = [];
  inv.filter((i) => stockState(i) === 'low').forEach((i) => a.push({ g: 'inventory', tone: 'neg', ic: 'package', text: L(`${i.name.en} is running low`, `${i.name.fr} : stock bas`), sub: `${fmt.num(i.onHand)} ${i.unit} · ${L('par', 'niveau')} ${fmt.num(i.par)}`, act: L('Reorder', 'Commander'), to: () => go('inventory', { tab: 'reorder' }) }));
  invoices.filter((v) => v.status === 'overdue').forEach((v) => a.push({ g: 'purchasing', tone: 'neg', ic: 'receipt', text: L(`Invoice ${v.id} is overdue`, `Facture ${v.id} en retard`), sub: `${sup(v.sup)} · ${fmt.money(v.amount)}`, act: L('Pay', 'Payer'), to: () => go('purchasing', { tab: 'invoices' }) }));
  invoices.filter((v) => v.status === 'due' && v.dueIn <= 3).forEach((v) => a.push({ g: 'purchasing', tone: 'warn', ic: 'receipt', text: L(`Invoice ${v.id} due in ${v.dueIn} days`, `Facture ${v.id} due dans ${v.dueIn} jours`), sub: `${sup(v.sup)} · ${fmt.money(v.amount)}`, act: L('View', 'Voir'), to: () => go('purchasing', { tab: 'invoices' }) }));
  pos.filter((p) => p.status === 'sent').forEach((p) => a.push({ g: 'purchasing', tone: 'acc', ic: 'truck', text: L(`${p.id} arrives ${fmt.date(p.expected, { weekday: 'short', month: 'short', day: 'numeric' })}`, `${p.id} arrive ${fmt.date(p.expected, { weekday: 'short', month: 'short', day: 'numeric' })}`), sub: `${sup(p.sup)} · ${p.lines.length} ${L('items to check in', 'articles à recevoir')}`, act: L('Receive', 'Recevoir'), to: () => go('purchasing', { tab: 'receiving' }) }));
  punches.filter((x) => x.flag === 'missing').forEach((x) => a.push({ g: 'team', tone: 'neg', ic: 'clock-countdown', text: L(`${first(x.emp)} forgot to punch out`, `${first(x.emp)} a oublié de pointer`), sub: fmt.date(x.date, { weekday: 'long', month: 'short', day: 'numeric' }), act: L('Fix', 'Corriger'), to: () => go('team', { tab: 'sheets' }) }));
  P.calc(employees, punches, now).filter((r) => r.otWeeks[1] > 0).forEach((r) => a.push({ g: 'team', tone: 'warn', ic: 'timer', text: L(`${r.e.name.split(' ')[0]} is headed for overtime`, `${r.e.name.split(' ')[0]} fera des heures supp.`), sub: `≈ ${fmt.num(Math.round(r.otWeeks[1] * 10) / 10)} h · 1,5×`, act: L('Schedule', 'Horaire'), to: () => go('team', { tab: 'schedule' }) }));
  O.temps.filter((t) => (t.hot ? t.v < t.lim : t.v > t.lim)).forEach((t) => a.push({ g: 'team', tone: 'neg', ic: 'thermometer-simple', text: L(`${t.name.en} at ${fmt.num(t.v)} °C`, `${t.name.fr} à ${fmt.num(t.v)} °C`), sub: L(`Limit ${t.lim} °C · logged ${t.t}`, `Limite ${t.lim} °C · noté à ${t.t}`), act: L('Check', 'Vérifier'), to: () => go('team', { tab: 'tasks' }) }));
  recipes.map((r) => ({ r, c: recipeCost(r, invMap) })).filter(({ c }) => c.fc > target + 3).forEach(({ r, c }) => a.push({ g: 'menu', tone: 'warn', ic: 'bowl-food', text: L(`${r.name.en} is above food-cost target`, `${r.name.fr} dépasse la cible`), sub: `${fmt.pct(c.fc)} · ${L('target', 'cible')} ${fmt.pct(target)}`, act: L('Reprice', 'Ajuster'), to: () => go('menu', { recipe: r.id }) }));
  a.push({ g: 'finance', tone: 'warn', ic: 'bank', text: L('GST/QST remittance due Saturday', 'Remise TPS/TVQ due samedi'), sub: fmt.money0(14200) + ' · Revenu Québec', act: L('Cash flow', 'Trésorerie'), to: () => go('finance', { tab: 'cash' }) });
  a.push({ g: 'finance', tone: 'warn', ic: 'users-three', text: L('Labour is over budget this month', 'Main-d’œuvre au-dessus du budget'), sub: `${fmt.money0(36110)} / ${fmt.money0(35500)}`, act: L('Budget', 'Budget'), to: () => go('finance', { tab: 'budget' }) });
  return a;
}

function AlertsCenter() {
  const { L } = useMizo();
  const all = useAlerts();
  const [g, setG] = React.useState('all');
  const groups = [['all', L('All', 'Toutes')], ['inventory', L('Inventory', 'Inventaire')], ['purchasing', L('Purchasing', 'Achats')], ['team', L('Team', 'Équipe')], ['menu', L('Menu', 'Menu')], ['finance', L('Finance', 'Finances')]];
  const label = Object.fromEntries(groups);
  const list = all.filter((a) => g === 'all' || a.g === g);
  return (
    <div className="page">
      <PageHead sub={L('Everything that needs a decision, from every part of the restaurant.', 'Tout ce qui demande une décision, dans tout le restaurant.')}>
        <Seg size="sm" value={g} onChange={setG} options={groups.map(([k, l]) => [k, l + ' ' + (k === 'all' ? all.length : all.filter((a) => a.g === k).length)])} />
      </PageHead>
      <section className="stats">
        <Stat label={L('Urgent', 'Urgent')} value={all.filter((a) => a.tone === 'neg').length} tone="neg">{L('Act today', 'À traiter aujourd’hui')}</Stat>
        <Stat label={L('Watch', 'À surveiller')} value={all.filter((a) => a.tone === 'warn').length} tone="warn">{L('This week', 'Cette semaine')}</Stat>
        <Stat label={L('Upcoming', 'À venir')} value={all.filter((a) => a.tone === 'acc').length} tone="acc">{L('Scheduled events', 'Événements prévus')}</Stat>
      </section>
      <div className="panel">
        <ul className="alerts">
          {list.map((a, i) => (
            <li key={i} className="alert">
              <span className={'alert-ic ' + a.tone}><Icon n={a.ic} /></span>
              <div className="alert-text"><div>{a.text}</div><div className="muted sm">{a.sub}</div></div>
              <span className="tag tag-neutral hide-sm">{label[a.g]}</span>
              <button className="btn btn-ghost" onClick={a.to}>{a.act}<Icon n="arrow-right" /></button>
            </li>
          ))}
          {!list.length ? <li className="empty">{L('Nothing here. Nice.', 'Rien ici. Bravo.')}</li> : null}
        </ul>
      </div>
    </div>
  );
}

function Activity() {
  const { L, lang, O } = useMizo();
  const [who, setWho] = React.useState('all');
  const people = [...new Set(O.activity.map((a) => a.who))];
  const list = O.activity.filter((a) => who === 'all' || a.who === who);
  return (
    <div className="page">
      <PageHead sub={L('A running log of who did what — counts, invoices, punches, changes.', 'Le journal de qui a fait quoi — inventaires, factures, pointages, changements.')}>
        <select className="input" value={who} onChange={(e) => setWho(e.target.value)} style={{ maxWidth: 220 }}><option value="all">{L('Everyone', 'Tout le monde')}</option>{people.map((p) => <option key={p}>{p}</option>)}</select>
      </PageHead>
      {[['today', L('Today · Wednesday, October 28', 'Aujourd’hui · mercredi 28 octobre')], ['yest', L('Yesterday', 'Hier')]].map(([d, t]) => {
        const rows = list.filter((a) => a.day === d); if (!rows.length) return null;
        return (
          <section key={d} className="panel">
            <h3>{t}</h3>
            <ul className="act">
              {rows.map((a, i) => <li key={i}><span className="act-t tnum">{a.t}</span><span className={'act-ic' + (a.who === 'MIZO' ? ' ai' : '')}><Icon n={a.ic} /></span><span><b>{a.who}</b> {a.what[lang]}</span></li>)}
            </ul>
          </section>
        );
      })}
    </div>
  );
}

const useAlertsCount = (c) => c.inv.filter((i) => stockState(i) === 'low').length + c.invoices.filter((v) => v.status === 'overdue' || (v.status === 'due' && v.dueIn <= 3)).length + c.punches.filter((p) => p.flag === 'missing').length;
Object.assign(window, { useAlertsCount, SECTIONS, SECTION_ALIAS, SectionHead, useAlerts, AlertsCenter, Activity });
