// Phase 1 closing layer: location switcher, export & print centre, simulated send / add-location flows.
function useLocations() {
  const { F, L, locs } = useMizo();
  return [...F.locations.map((l) => ({ ...l, demo: true })), ...locs];
}
function locLabel(l, L, lang) { return l.id === 'all' ? L('All locations', 'Tous les restaurants') : l.name.replace('Souvlaki Village — ', ''); }

function LocationSwitcher() {
  const { L, lang, loc, setLoc, go, openAddLoc, D } = useMizo();
  const [open, setOpen] = React.useState(false); const ref = React.useRef(null);
  const all = useLocations(), cur = all.find((l) => l.id === loc);
  React.useEffect(() => { if (!open) return; const c = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); }; const k = (e) => e.key === 'Escape' && setOpen(false); document.addEventListener('mousedown', c); window.addEventListener('keydown', k); return () => { document.removeEventListener('mousedown', c); window.removeEventListener('keydown', k); }; }, [open]);
  const sub = loc === 'all' ? L(`${all.length} locations · combined view`, `${all.length} restaurants · vue combinée`) : cur && cur.status === 'open' ? (cur.id === 'parc' ? 'Avenue du Parc · Montréal' : cur.city || '') : L('Planned · projection only', 'Prévu · projection seulement');
  const pick = (id) => { setLoc(id); setOpen(false); };
  return (
    <div className="venue locsw" ref={ref}>
      <button className="locsw-btn" onClick={() => setOpen(!open)} aria-haspopup="listbox" aria-expanded={open} aria-label={L('Change location', 'Changer de restaurant')}>
        <span className="venue-dot"><Icon n={loc === 'all' ? 'buildings' : 'fork-knife'} /></span>
        <div style={{ minWidth: 0 }}><div className="venue-name">{loc === 'all' ? L('All locations', 'Tous les restaurants') : D.restaurant.name + (cur && cur.id !== 'parc' ? ' · ' + locLabel(cur, L, lang) : '')}</div><div className="venue-sub">{sub}</div></div>
        <Icon n="caret-up-down" className="muted locsw-caret" />
      </button>
      {open ? <div className="locsw-pop" role="listbox" aria-label={L('Locations', 'Restaurants')}>
        <div className="locsw-g">{L('Your locations', 'Vos restaurants')}</div>
        {all.map((l) => <button key={l.id} role="option" aria-selected={loc === l.id} className={'locsw-item' + (loc === l.id ? ' on' : '')} onClick={() => pick(l.id)}>
          <Icon n={l.status === 'open' ? 'storefront' : 'map-pin'} />
          <span><b>{locLabel(l, L, lang)}</b><span className="muted sm">{l.status === 'open' ? L('Open · demo data', 'Ouvert · données démo') : (l.opens ? l.opens[lang] : L('Planned', 'Prévu')) + (l.demo ? '' : ' · ' + L('added this session', 'ajouté cette session'))}</span></span>
          {loc === l.id ? <Icon n="check" className="txt-acc" /> : null}
        </button>)}
        <button role="option" aria-selected={loc === 'all'} className={'locsw-item' + (loc === 'all' ? ' on' : '')} onClick={() => pick('all')}><Icon n="buildings" /><span><b>{L('All locations', 'Tous les restaurants')}</b><span className="muted sm">{L('Consolidated totals', 'Totaux consolidés')}</span></span>{loc === 'all' ? <Icon n="check" className="txt-acc" /> : null}</button>
        <div className="locsw-sep"></div>
        <button className="locsw-item act" onClick={() => { setOpen(false); go('finance', { tab: 'locations' }); }}><Icon n="columns" /><span>{L('Compare locations', 'Comparer les restaurants')}</span></button>
        <button className="locsw-item act" onClick={() => { setOpen(false); openAddLoc(); }}><Icon n="plus" /><span>{L('Add a location', 'Ajouter un restaurant')}</span></button>
        <div className="locsw-note muted sm"><Icon n="flask" />{L('Demonstration data. Accounts with several locations come in Phase 2.', 'Données de démonstration. Les comptes multi-restaurants arrivent en phase 2.')}</div>
      </div> : null}
    </div>
  );
}

function LocBanner({ sec }) {
  const { L, lang, loc, setLoc, go } = useMizo();
  const all = useLocations(), cur = all.find((l) => l.id === loc);
  if (loc === 'parc' || !cur && loc !== 'all') return null;
  const fin = sec === 'finance';
  const t = loc === 'all'
    ? (fin ? L('Combined view. Only Avenue du Parc has actual results — planned locations add nothing until they open. See Finance › Locations for the projection.', 'Vue combinée. Seul Avenue du Parc a des résultats réels — les restaurants prévus n’ajoutent rien avant leur ouverture. Voir Finances › Restaurants pour la projection.') : L('Combined view. Avenue du Parc is the only open location, so these numbers are its numbers.', 'Vue combinée. Avenue du Parc est le seul restaurant ouvert : ces chiffres sont les siens.'))
    : L(`${locLabel(cur, L, lang)} isn’t open yet, so there’s no stock, sales or staff to show. You’re seeing Avenue du Parc for reference.`, `${locLabel(cur, L, lang)} n’est pas encore ouvert : aucun stock, vente ni personnel. Vous voyez Avenue du Parc à titre de référence.`);
  return <div className="loc-banner"><Icon n={loc === 'all' ? 'buildings' : 'map-pin'} /><span>{t}</span><div className="itools">{loc !== 'all' ? <button className="btn btn-ghost" onClick={() => go('finance', { tab: 'locations' })}>{L('See the projection', 'Voir la projection')}</button> : null}<button className="btn btn-secondary" onClick={() => setLoc('parc')}>{L('Back to Avenue du Parc', 'Revenir à Avenue du Parc')}</button></div></div>;
}

function AddLocationModal({ open, onClose }) {
  const { L, locs, setLocs, setLoc, toast } = useMizo();
  const f0 = { name: '', address: '', city: '', seats: '', opens: '', status: 'planned' };
  const [f, setF] = React.useState(f0), [errs, setErrs] = React.useState({}), [done, setDone] = React.useState(null);
  React.useEffect(() => { if (open) { setF(f0); setErrs({}); setDone(null); } }, [open]);
  const save = () => { const e = { name: vReq(f.name, L), city: vReq(f.city, L), seats: f.seats && Number(f.seats) > 0 ? null : L('Enter a number above 0.', 'Entrez un nombre supérieur à 0.') }; setErrs(e); if (Object.values(e).some(Boolean)) return; const id = 'loc' + (locs.length + 3); const l = { id, name: 'Souvlaki Village — ' + f.name, city: f.city, address: f.address, seats: Number(f.seats), status: 'planned', opens: f.opens ? { en: 'Opens ' + f.opens, fr: 'Ouverture ' + f.opens } : { en: 'Planned', fr: 'Prévu' } }; setLocs([...locs, l]); setDone(l); };
  return (
    <Modal open={open} onClose={onClose} title={<span className="wiz-title"><Icon n="map-pin" />{L('Add a location', 'Ajouter un restaurant')}</span>} actions={done ? <><button className="btn btn-secondary" onClick={onClose}>{L('Close', 'Fermer')}</button><button className="btn btn-primary" onClick={() => { setLoc(done.id); onClose(); toast(L('Switched to the new location', 'Nouveau restaurant sélectionné')); }}>{L('Switch to it', 'Y passer')}<Icon n="arrow-right" /></button></> : <><button className="btn btn-secondary" onClick={onClose}>{L('Cancel', 'Annuler')}</button><button className="btn btn-primary" onClick={save}><Icon n="plus" />{L('Add location', 'Ajouter')}</button></>}>
      {done ? <div className="px-done"><span className="empty-ic"><Icon n="check" /></span><b>{done.name}</b><p className="muted">{L('Added for this session as a planned location. It appears in the location switcher and in Finance › Locations. It isn’t saved after you close MIZO — accounts with several locations come in Phase 2.', 'Ajouté pour cette session comme restaurant prévu. Il apparaît dans le sélecteur et dans Finances › Restaurants. Il n’est pas conservé après fermeture — les comptes multi-restaurants arrivent en phase 2.')}</p></div> : <>
        <div className="suggest"><Icon n="info" /><div>{L('New locations start as “planned”. Stock, menu and staff can be copied from Avenue du Parc when the location opens (Phase 2).', 'Les nouveaux restaurants commencent comme « prévus ». Stock, menu et personnel pourront être copiés d’Avenue du Parc à l’ouverture (phase 2).')}</div></div>
        <div className="form-grid">
          <Field span label={L('Location name', 'Nom du restaurant')} id="al-n" error={errs.name} hint={L('Shown after “Souvlaki Village —”, e.g. Plateau', 'Affiché après « Souvlaki Village — », ex. Plateau')}><input id="al-n" className="input" value={f.name} onChange={(e) => setF({ ...f, name: e.target.value })} /></Field>
          <Field span label={L('Street address', 'Adresse')} id="al-a" hint={L('Optional for now', 'Facultatif pour l’instant')}><input id="al-a" className="input" value={f.address} onChange={(e) => setF({ ...f, address: e.target.value })} /></Field>
          <Field label={L('City', 'Ville')} id="al-c" error={errs.city}><input id="al-c" className="input" value={f.city} onChange={(e) => setF({ ...f, city: e.target.value })} /></Field>
          <Field label={L('Seats', 'Places')} id="al-s" error={errs.seats}><input id="al-s" className="input" type="number" min="0" value={f.seats} onChange={(e) => setF({ ...f, seats: e.target.value })} /></Field>
          <Field span label={L('Expected opening', 'Ouverture prévue')} id="al-o" hint={L('Optional', 'Facultatif')}><input id="al-o" className="input" type="month" value={f.opens} onChange={(e) => setF({ ...f, opens: e.target.value })} /></Field>
        </div>
      </>}
    </Modal>
  );
}

function SimSendModal({ open, onClose, title, to, subject, lines, cta }) {
  const { L } = useMizo();
  const [rcpt, setRcpt] = React.useState(to || ''), [err, setErr] = React.useState(null), [sent, setSent] = React.useState(false);
  React.useEffect(() => { if (open) { setRcpt(to || ''); setErr(null); setSent(false); } }, [open]);
  const go = () => { const e = vReq(rcpt, L) || vEmail(rcpt, L); setErr(e); if (!e) setSent(true); };
  return (
    <Modal open={open} onClose={onClose} title={<span className="wiz-title"><Icon n="envelope-simple" />{title}</span>} actions={sent ? <button className="btn btn-primary" onClick={onClose}>{L('Done', 'Terminé')}</button> : <><button className="btn btn-secondary" onClick={onClose}>{L('Cancel', 'Annuler')}</button><button className="btn btn-primary" onClick={go}><Icon n="paper-plane-tilt" />{cta || L('Simulate sending', 'Simuler l’envoi')}</button></>}>
      {sent ? <div className="px-done"><span className="empty-ic"><Icon n="flask" /></span><b>{L('Simulated — nothing was sent', 'Simulé — rien n’a été envoyé')}</b><p className="muted">{L(`In Phase 2 this message goes to ${rcpt}. Email delivery isn’t connected yet.`, `En phase 2, ce message ira à ${rcpt}. L’envoi de courriels n’est pas encore connecté.`)}</p></div> : <>
        <Field label={L('Send to', 'Envoyer à')} id="ss-to" error={err}><input id="ss-to" className="input" type="email" value={rcpt} onChange={(e) => setRcpt(e.target.value)} /></Field>
        <div className="dr-label">{L('Preview', 'Aperçu')}</div>
        <div className="mail-prev"><div className="mail-h"><span className="muted sm">{L('From', 'De')}</span> MIZO &lt;bonjour@mizo.app&gt;<br /><span className="muted sm">{L('Subject', 'Objet')}</span> <b>{subject}</b></div><div className="mail-b">{lines.map((x, i) => <p key={i}>{x}</p>)}</div></div>
        <div className="muted sm"><Icon n="flask" /> {L('Demo: email delivery comes in Phase 2.', 'Démo : l’envoi de courriels arrive en phase 2.')}</div>
      </>}
    </Modal>
  );
}

const PX_REPORTS = [
  ['fin', [['pnl', 'file-text', ['Profit & loss', 'État des résultats']], ['summary', 'chart-pie-slice', ['Financial summary', 'Sommaire financier']]], ['Financial', 'Finances']],
  ['inv', [['stock', 'package', ['Inventory valuation', 'Valeur de l’inventaire']], ['count', 'clipboard-text', ['Count sheet (blank)', 'Feuille de comptage (vierge)']], ['waste', 'trash', ['Waste report', 'Rapport des pertes']]], ['Inventory', 'Inventaire']],
  ['po', [['po', 'receipt', ['Purchase order', 'Bon de commande']]], ['Purchasing', 'Achats']],
];

function PxDoc({ kind, poId, opt, docL, dfmt }) {
  const c = useMizo(); const { D, O, inv, pos, invMap, waste, fin, loc } = c;
  const L = docL, lg = opt.lang, m = dfmt.money0, mm = dfmt.money;
  const R = D.restaurant, today = dfmt.date('2026-10-28', { year: 'numeric', month: 'long', day: 'numeric' });
  const head = (title, sub) => <div className="pd-head"><div><div className="pd-brand">{R.name}</div><div className="pd-addr">{loc === 'all' ? L('All locations (consolidated)', 'Tous les restaurants (consolidé)') : R.address}</div></div><div className="pd-title"><h1>{title}</h1><div>{sub}</div></div></div>;
  const foot = <div className="pd-foot"><span>{L('Prepared with MIZO on', 'Préparé avec MIZO le')} {today}</span><span>{L('Demonstration data — not for filing', 'Données de démonstration — ne pas soumettre')}</span></div>;
  const tag = (p) => (opt.prov ? <span className={'pd-prov ' + p}>{{ v: L('verified', 'vérifié'), e: L('estimate', 'estimé'), m: L('missing', 'manquant') }[p]}</span> : null);
  if (kind === 'pnl' || kind === 'summary') {
    const P = finPeriod(opt.period, fin.c, L), a = P.cur, b = P.cmp, live = !P.closed;
    if (kind === 'summary') return <div className="pd">{head(L('Financial summary', 'Sommaire financier'), P.lab)}
      <div className="pd-kpis">{[[L('Revenue', 'Ventes'), m(a.rev), 'v'], [L('Gross profit', 'Profit brut'), m(a.gross) + ' · ' + dfmt.pct(a.grossPct), live ? 'e' : 'v'], [L('Operating profit (estimate)', 'Profit d’exploitation (estimé)'), m(a.op) + ' · ' + dfmt.pct(a.opPct), 'e'], [L('Food cost', 'Coût alimentaire'), dfmt.pct(a.foodPct), 'e'], [L('Labour', 'Main-d’œuvre'), dfmt.pct(a.labPct), 'e'], [L('Prime cost', 'Coût principal'), dfmt.pct(a.primePct), 'e']].map(([n, v, p]) => <div key={n}><span>{n} {tag(p)}</span><b>{v}</b></div>)}</div>
      <table className="pd-t"><thead><tr><th>{L('Compared with', 'Comparé à')} {P.cmpLab}</th><th>{L('This period', 'Cette période')}</th><th>{L('Comparison', 'Comparaison')}</th><th>{L('Change', 'Écart')}</th></tr></thead><tbody>{[[L('Revenue', 'Ventes'), a.rev, b.rev], [L('Gross profit', 'Profit brut'), a.gross, b.gross], [L('Labour', 'Main-d’œuvre'), a.lab, b.lab], [L('Operating profit (est.)', 'Profit d’exploitation (est.)'), a.op, b.op]].map(([n, x, y]) => <tr key={n}><td>{n}</td><td>{m(x)}</td><td>{m(y)}</td><td>{(x - y >= 0 ? '+' : '−') + m(Math.abs(x - y))}</td></tr>)}</tbody></table>
      {opt.notes ? <p className="pd-note">{L('Operating profit is before depreciation, interest, insurance, owner pay and income tax. It is not net profit.', 'Le profit d’exploitation est avant amortissement, intérêts, assurances, rémunération de la propriétaire et impôt. Ce n’est pas le profit net.')}</p> : null}{foot}</div>;
    const ln = (n, x, y, p, cls) => <tr className={cls || ''}><td>{n} {p ? tag(p) : null}</td><td>{m(x)}</td><td>{dfmt.pct((x / a.rev) * 100)}</td><td>{m(y)}</td></tr>;
    return <div className="pd">{head(L('Profit & loss', 'État des résultats'), P.lab + ' · ' + L('vs', 'vs') + ' ' + P.cmpLab)}
      <table className="pd-t pd-pl"><thead><tr><th></th><th>{L('This period', 'Cette période')}</th><th>{L('% of sales', '% des ventes')}</th><th>{P.cmpLab}</th></tr></thead><tbody>
        <tr className="sec"><td colSpan="4">{L('Revenue', 'Revenus')}</td></tr>{ln(L('Food sales', 'Ventes d’aliments'), a.foodRev, b.foodRev, 'v')}{ln(L('Beverage sales', 'Ventes de boissons'), a.bevRev, b.bevRev, 'v')}{ln(L('Total revenue', 'Total des revenus'), a.rev, b.rev, null, 'tot')}
        <tr className="sec"><td colSpan="4">{L('Cost of goods sold', 'Coût des marchandises vendues')}</td></tr>{ln(L('Food', 'Aliments'), a.foodCogs, b.foodCogs, 'e')}{ln(L('Beverages', 'Boissons'), a.bevCogs, b.bevCogs, 'e')}{ln(L('Packaging', 'Emballages'), a.pack, b.pack, 'v')}{ln(L('Gross profit', 'Profit brut'), a.gross, b.gross, live ? 'e' : 'v', 'tot')}
        <tr className="sec"><td colSpan="4">{L('Labour', 'Main-d’œuvre')}</td></tr>{ln(L('Wages, employer costs & vacation', 'Salaires, charges et vacances'), a.lab, b.lab, live ? 'e' : 'v')}{ln(L('Prime cost (goods + labour)', 'Coût principal'), a.prime, b.prime, 'e', 'sub')}
        <tr className="sec"><td colSpan="4">{L('Operating costs', 'Frais d’exploitation')}</td></tr>{ln(L('Rent', 'Loyer'), a.rent, b.rent, 'v')}{ln(L('Utilities', 'Services publics'), a.util, b.util, 'e')}{ln(L('Card fees, delivery commissions & other', 'Frais de carte, commissions et autres'), a.other, b.other, 'v')}
        {ln(L('Operating profit (estimate)', 'Profit d’exploitation (estimé)'), a.op, b.op, 'e', 'tot big')}
      </tbody></table>
      {opt.notes ? <p className="pd-note">{L('Not net profit: depreciation (est. $1,850/mo), interest, insurance (about $640/mo), owner pay and income tax are not deducted. Lines marked “estimate” use the time clock, the last inventory count or last year’s utility bills.', 'Ce n’est pas le profit net : amortissement (env. 1 850 $/mois), intérêts, assurances (env. 640 $/mois), rémunération et impôt ne sont pas déduits. Les lignes « estimé » utilisent le pointage, le dernier inventaire ou les factures de l’an dernier.')}</p> : null}{foot}</div>;
  }
  if (kind === 'stock' || kind === 'count') {
    const cats = Object.keys(D.cats); const tot = inv.reduce((s, i) => s + i.onHand * i.cost, 0);
    return <div className="pd">{head(kind === 'stock' ? L('Inventory valuation', 'Valeur de l’inventaire') : L('Inventory count sheet', 'Feuille de comptage'), kind === 'stock' ? L('On hand as of', 'En stock au') + ' ' + today : L('Count date: ____________   Counted by: ____________', 'Date : ____________   Compté par : ____________'))}
      <table className="pd-t"><thead><tr><th>{L('Item', 'Article')}</th><th>{L('Unit', 'Unité')}</th>{kind === 'stock' ? <><th>{L('On hand', 'En stock')}</th><th>{L('Unit cost', 'Coût unitaire')}</th><th>{L('Value', 'Valeur')}</th></> : <><th>{L('Par', 'Niveau')}</th><th>{L('Storage', 'Lieu')}</th><th className="pd-blank">{L('Count', 'Compte')}</th></>}</tr></thead>
        <tbody>{cats.map((k) => { const items = inv.filter((i) => i.cat === k); if (!items.length) return null; return <React.Fragment key={k}><tr className="sec"><td colSpan="5">{D.cats[k][lg]}{kind === 'stock' ? ' · ' + m(items.reduce((s, i) => s + i.onHand * i.cost, 0)) : ''}</td></tr>{items.map((i) => <tr key={i.id}><td>{i.name[lg]}</td><td>{i.unit}</td>{kind === 'stock' ? <><td>{dfmt.num(i.onHand)}</td><td>{mm(i.cost)}</td><td>{mm(i.onHand * i.cost)}</td></> : <><td>{dfmt.num(i.par)}</td><td>{O.meta[i.id] ? (O.locations.find((x) => x.id === O.meta[i.id][0]) || { name: { en: '', fr: '' } }).name[lg] : ''}</td><td className="pd-blank"></td></>}</tr>)}</React.Fragment>; })}
          {kind === 'stock' ? <tr className="tot big"><td colSpan="4">{L('Total inventory value', 'Valeur totale')}</td><td>{mm(tot)}</td></tr> : null}</tbody></table>
      {opt.notes && kind === 'stock' ? <p className="pd-note">{L('Quantities are from the last full count (Oct 25) plus deliveries and minus sales since. Values use the latest invoice price.', 'Quantités : dernier inventaire complet (25 oct.) plus livraisons, moins ventes. Valeurs au dernier prix facturé.')}</p> : null}{foot}</div>;
  }
  if (kind === 'waste') {
    const rows = waste.map((w) => ({ ...w, i: invMap[w.ing] })).filter((w) => w.i); const tot = rows.reduce((s, w) => s + w.qty * w.i.cost, 0);
    return <div className="pd">{head(L('Waste report', 'Rapport des pertes'), dfmt.date(rows[rows.length - 1].date) + ' – ' + dfmt.date(rows[0].date))}
      <table className="pd-t"><thead><tr><th>{L('Date', 'Date')}</th><th>{L('Item', 'Article')}</th><th>{L('Qty', 'Qté')}</th><th>{L('Reason', 'Raison')}</th><th>{L('By', 'Par')}</th><th>{L('Cost', 'Coût')}</th></tr></thead><tbody>{rows.map((w) => <tr key={w.id}><td>{dfmt.date(w.date)}</td><td>{w.i.name[lg]}</td><td>{dfmt.num(w.qty)} {w.i.unit}</td><td>{O.wasteReasons[w.reason][lg]}</td><td>{w.by}</td><td>{mm(w.qty * w.i.cost)}</td></tr>)}<tr className="tot big"><td colSpan="5">{L('Total', 'Total')}</td><td>{mm(tot)}</td></tr></tbody></table>{foot}</div>;
  }
  const p = pos.find((x) => x.id === poId) || pos[0], s = D.suppliers.find((x) => x.id === p.sup), si = O.supInfo[p.sup];
  const lines = p.lines.map(([id, q]) => ({ i: invMap[id], q })).filter((x) => x.i), sub = lines.reduce((a, x) => a + x.q * x.i.cost, 0);
  return <div className="pd">{head(L('Purchase order', 'Bon de commande'), p.id)}
    <div className="pd-parties"><div><span>{L('Supplier', 'Fournisseur')}</span><b>{s.name}</b>{s.contact}<br />{si ? si.email : ''} · {s.phone}</div><div><span>{L('Deliver to', 'Livrer à')}</span><b>{R.name}</b>{R.address}<br />{R.phone}</div><div><span>{L('Dates', 'Dates')}</span>{L('Ordered', 'Commandé')}: {dfmt.date(p.created, { year: 'numeric', month: 'short', day: 'numeric' })}<br />{L('Expected', 'Prévu')}: <b>{dfmt.date(p.expected, { weekday: 'short', month: 'short', day: 'numeric' })}</b><br />{L('Terms', 'Modalités')}: {si ? si.terms + ' ' + L('days', 'jours') : '—'}</div></div>
    <table className="pd-t"><thead><tr><th>{L('Item', 'Article')}</th><th>{L('Pack', 'Format')}</th><th>{L('Qty', 'Qté')}</th><th>{L('Unit price', 'Prix unitaire')}</th><th>{L('Line total', 'Total')}</th></tr></thead><tbody>{lines.map(({ i, q }) => <tr key={i.id}><td>{i.name[lg]}</td><td>{O.meta[i.id] ? O.meta[i.id][2][lg] : ''}</td><td>{dfmt.num(q)} {i.unit}</td><td>{mm(i.cost)}</td><td>{mm(q * i.cost)}</td></tr>)}
      <tr className="tot"><td colSpan="4">{L('Subtotal (before taxes)', 'Sous-total (avant taxes)')}</td><td>{mm(sub)}</td></tr></tbody></table>
    {p.note && opt.notes ? <p className="pd-note">{L('Note', 'Note')}: {p.note[lg]}</p> : null}
    <div className="pd-sign"><div>{L('Approved by', 'Approuvé par')}<span></span></div><div>{L('Received by / date', 'Reçu par / date')}<span></span></div></div>{foot}</div>;
}

function ExportDialog({ open, onClose, init }) {
  const c = useMizo(); const { L, lang, fin, pos, setup, D } = c;
  const [kind, setKind] = React.useState('pnl'), [poId, setPoId] = React.useState(null), [sim, setSim] = React.useState(false);
  const [opt, setOpt] = React.useState({ lang, period: fin.p, paper: 'letter', prov: true, notes: true });
  React.useEffect(() => { if (open) { setKind((init && init.kind) || 'pnl'); setPoId((init && init.id) || (pos[0] && pos[0].id)); setOpt({ lang, period: fin.p, paper: setup.cur === 'EUR' ? 'a4' : 'letter', prov: true, notes: true }); setSim(false); } }, [open]);
  if (!open) return null;
  const docL = (en, fr) => (opt.lang === 'fr' ? fr : en), dfmt = makeFmt(opt.lang, setup.cur);
  const print = () => { const st = document.createElement('style'); st.id = 'px-page'; st.textContent = `@page{size:${opt.paper === 'a4' ? 'A4' : 'letter'};margin:14mm}`; document.head.appendChild(st); document.body.classList.add('px-printing'); const done = () => { document.body.classList.remove('px-printing'); st.remove(); window.removeEventListener('afterprint', done); }; window.addEventListener('afterprint', done); setTimeout(() => { window.print(); setTimeout(done, 1500); }, 50); };
  const name = PX_REPORTS.flatMap((g) => g[1]).find((x) => x[0] === kind);
  return ReactDOM.createPortal(
    <div className="dialog-backdrop mdl-backdrop px-wrap" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
      <div className="px" role="dialog" aria-modal="true" aria-label={L('Print or export', 'Imprimer ou exporter')}>
        <aside className="px-side">
          <div className="px-top"><h2>{L('Print or save as PDF', 'Imprimer ou enregistrer en PDF')}</h2><button className="btn btn-icon btn-secondary" onClick={onClose} aria-label={L('Close', 'Fermer')}><Icon n="x" /></button></div>
          {PX_REPORTS.map(([g, items, gl]) => <div key={g} className="px-g"><div className="dr-label">{L(...gl)}</div>{items.map(([k, ic, t]) => <button key={k} className={'px-r' + (kind === k ? ' on' : '')} onClick={() => setKind(k)}><Icon n={ic} />{L(...t)}</button>)}</div>)}
          {kind === 'po' ? <Field label={L('Which order', 'Quelle commande')} id="px-po"><select id="px-po" className="input" value={poId || ''} onChange={(e) => setPoId(e.target.value)}>{pos.map((p) => <option key={p.id} value={p.id}>{p.id} · {D.suppliers.find((s) => s.id === p.sup).name}</option>)}</select></Field> : null}
          {kind === 'pnl' || kind === 'summary' ? <Field label={L('Period', 'Période')} id="px-per"><select id="px-per" className="input" value={opt.period} onChange={(e) => setOpt({ ...opt, period: e.target.value })}>{FIN_PERIODS.map(([k, en, fr]) => <option key={k} value={k}>{L(en, fr)}</option>)}</select></Field> : null}
          <div className="px-opts">
            <div className="set-row"><span>{L('Document language', 'Langue du document')}</span><Seg size="sm" value={opt.lang} onChange={(v) => setOpt({ ...opt, lang: v })} options={[['en', 'EN'], ['fr', 'FR']]} /></div>
            <div className="set-row"><span>{L('Paper', 'Papier')}</span><Seg size="sm" value={opt.paper} onChange={(v) => setOpt({ ...opt, paper: v })} options={[['letter', 'Letter'], ['a4', 'A4']]} /></div>
            {kind === 'pnl' || kind === 'summary' ? <div className="set-row"><span>{L('Show verified / estimate labels', 'Afficher vérifié / estimé')}</span><Toggle on={opt.prov} label="prov" onChange={(v) => setOpt({ ...opt, prov: v })} /></div> : null}
            <div className="set-row"><span>{L('Include notes', 'Inclure les notes')}</span><Toggle on={opt.notes} label="notes" onChange={(v) => setOpt({ ...opt, notes: v })} /></div>
          </div>
          <div className="px-acts">
            <button className="btn btn-primary btn-block" onClick={print}><Icon n="printer" />{L('Print or save as PDF', 'Imprimer ou enregistrer en PDF')}</button>
            <p className="muted sm" style={{ margin: 0 }}><Icon n="check-circle" className="txt-pos" /> {L('Real file: opens your browser’s print window. Choose “Save as PDF” to get a PDF on your computer.', 'Fichier réel : ouvre la fenêtre d’impression. Choisissez « Enregistrer en PDF » pour obtenir un PDF.')}</p>
            <button className="btn btn-secondary btn-block" onClick={() => setSim(true)}><Icon n={kind === 'po' ? 'envelope-simple' : 'cloud-arrow-down'} />{kind === 'po' ? L('Email PDF to supplier', 'Envoyer le PDF au fournisseur') : L('Download from MIZO (server PDF)', 'Télécharger depuis MIZO (PDF serveur)')}<span className="sim-tag" style={{ marginLeft: 'auto' }}>{L('Simulated', 'Simulé')}</span></button>
            {sim ? <div className="suggest warn-s"><Icon n="flask" /><div><b>{L('Simulated — no file was created or sent', 'Simulé — aucun fichier créé ni envoyé')}</b><br /><span className="sm">{kind === 'po' ? L('In Phase 2, MIZO will generate this PDF and email it to the supplier. Use “Print or save as PDF” today and attach it yourself.', 'En phase 2, MIZO générera ce PDF et l’enverra au fournisseur. Aujourd’hui, utilisez « Imprimer ou enregistrer » et joignez-le vous-même.') : L('In Phase 2, MIZO will generate and store this PDF on the server. Use “Print or save as PDF” today.', 'En phase 2, MIZO générera et conservera ce PDF. Aujourd’hui, utilisez « Imprimer ou enregistrer ».')}</span></div></div> : null}
          </div>
        </aside>
        <div className="px-stage"><div className="px-cap muted sm">{L('Preview', 'Aperçu')} · {L(...name[2])} · {opt.paper === 'a4' ? 'A4' : 'Letter'}</div><div className={'px-paper ' + opt.paper}><PxDoc kind={kind} poId={poId} opt={opt} docL={docL} dfmt={dfmt} /></div></div>
      </div>
    </div>, document.body);
}

Object.assign(window, { useLocations, locLabel, LocationSwitcher, LocBanner, AddLocationModal, SimSendModal, PX_REPORTS, PxDoc, ExportDialog });
