const SETUP_STEPS = [
  ['lang', 'translate', ['Language & currency', 'Langue et devise']],
  ['restaurant', 'storefront', ['Your restaurant', 'Votre restaurant']],
  ['inventory', 'microsoft-excel-logo', ['Inventory', 'Inventaire']],
  ['suppliers', 'truck', ['Suppliers', 'Fournisseurs']],
  ['recipes', 'cooking-pot', ['Recipes', 'Recettes']],
  ['target', 'target', ['Food cost target', 'Cible de coût']],
  ['pos', 'cash-register', ['Point of sale', 'Point de vente']],
  ['explore', 'compass', ['Explore', 'Découvrir']],
];
const SETUP0 = { seen: false, step: 0, done: {}, hide: false, cur: 'CAD', region: 'QC', r: null, sups: [], rec: null, pos: null };
const POS_LIST = [['lightspeed', 'Lightspeed Restaurant'], ['square', 'Square for Restaurants'], ['clover', 'Clover'], ['toast', 'Toast'], ['maitred', 'Maitre’D'], ['other', null]];

function SetupWizard({ open, onClose, onTour }) {
  const c = useMizo(); const { L, lang, setLang, D, target, setTarget, setup, setSetup, openImport, toast, recipes, fmt } = c;
  const [errs, setErrs] = React.useState({});
  const [sup, setSup] = React.useState({ name: '', email: '', phone: '' });
  const [mail, setMail] = React.useState(false);
  const S = setup, i = Math.min(S.step, SETUP_STEPS.length - 1), key = SETUP_STEPS[i][0];
  const r = S.r || { name: D.restaurant.name, address: D.restaurant.address, phone: D.restaurant.phone, seats: D.restaurant.seats, kind: 'casual' };
  const upd = (p) => setSetup({ ...S, ...p });
  React.useEffect(() => { const k = (e) => e.key === 'Escape' && onClose(); if (open) window.addEventListener('keydown', k); return () => window.removeEventListener('keydown', k); }, [open]);
  if (!open) return null;
  const done = (k, extra) => setSetup({ ...S, ...extra, done: { ...S.done, [k]: true }, step: Math.min(i + 1, SETUP_STEPS.length - 1) });
  const next = () => {
    if (key === 'restaurant') { const e = { name: vReq(r.name, L), address: vReq(r.address, L), phone: vPhone(r.phone, L), seats: r.seats && Number(r.seats) > 0 ? null : L('Enter how many seats you have — an estimate is fine.', 'Entrez le nombre de places — une estimation suffit.') }; setErrs(e); if (Object.values(e).some(Boolean)) return; }
    if (key === 'explore') { setSetup({ ...S, done: { ...S.done, explore: true } }); onClose(); return; }
    done(key);
  };
  const addSup = () => { const e = { sname: vReq(sup.name, L), semail: vEmail(sup.email, L), sphone: vPhone(sup.phone, L) }; setErrs(e); if (Object.values(e).some(Boolean)) return; upd({ sups: [...S.sups, sup] }); setSup({ name: '', email: '', phone: '' }); toast(L(`${sup.name} added`, `${sup.name} ajouté`)); };
  const tpl = () => { const rows = [['Item name', 'Category', 'Quantity on hand', 'Unit', 'Unit cost', 'Supplier'], ['Feta (PDO)', 'Dairy', '18', 'kg', '14.50', 'Aegean Imports']]; const a = document.createElement('a'); a.href = URL.createObjectURL(new Blob([rows.map((x) => x.join(',')).join('\n')], { type: 'text/csv' })); a.download = 'mizo-inventory-template.csv'; a.click(); toast(L('Template downloaded', 'Modèle téléchargé')); };
  const nDone = SETUP_STEPS.filter(([k]) => S.done[k]).length;
  const opt = (on, ic, t, d, fn) => <button className={'ob-opt' + (on ? ' on' : '')} onClick={fn} aria-pressed={!!on}><span className="ob-opt-ic"><Icon n={ic} /></span><span><b>{t}</b>{d ? <span className="muted">{d}</span> : null}</span>{on ? <Icon n="check-circle" className="ob-opt-ck" /> : null}</button>;
  const ex = recipes.find((x) => x.id === 'chpita');
  const body = {
    lang: <>
      <p className="ob-lede">{L('Choose the language you’re most comfortable with. You can switch any time with EN / FR at the top of the screen.', 'Choisissez la langue qui vous convient. Vous pouvez changer à tout moment avec EN / FR en haut de l’écran.')}</p>
      <div className="ob-opts two">{opt(lang === 'en', 'translate', 'English', 'Canada', () => setLang('en'))}{opt(lang === 'fr', 'translate', 'Français', 'Canada / Québec', () => setLang('fr'))}</div>
      <div className="form-grid">
        <Field label={L('Currency', 'Devise')} id="ob-cur" hint={L('Amounts across MIZO use this currency.', 'Tous les montants utilisent cette devise.')}><select id="ob-cur" className="input" value={S.cur} onChange={(e) => upd({ cur: e.target.value })}><option value="CAD">{L('Canadian dollar (CAD $)', 'Dollar canadien (CAD $)')}</option><option value="USD">{L('US dollar (USD $)', 'Dollar américain (USD $)')}</option><option value="EUR">{L('Euro (EUR €)', 'Euro (EUR €)')}</option></select></Field>
        <Field label={L('Province (for sales tax)', 'Province (taxes de vente)')} id="ob-reg" hint={S.region === 'QC' ? L('GST 5% + QST 9.975%', 'TPS 5 % + TVQ 9,975 %') : S.region === 'ON' ? L('HST 13%', 'TVH 13 %') : L('GST 5%', 'TPS 5 %')}><select id="ob-reg" className="input" value={S.region} onChange={(e) => upd({ region: e.target.value })}><option value="QC">Québec</option><option value="ON">Ontario</option><option value="BC">{L('British Columbia', 'Colombie-Britannique')}</option><option value="AB">Alberta</option></select></Field>
      </div>
    </>,
    restaurant: <>
      <p className="ob-lede">{L('The basics. This appears on purchase orders you send to suppliers.', 'L’essentiel. Ces informations figurent sur vos bons de commande.')}</p>
      <div className="form-grid">
        <Field span label={L('Restaurant name', 'Nom du restaurant')} id="ob-n" error={errs.name}><input id="ob-n" className="input" value={r.name} onChange={(e) => upd({ r: { ...r, name: e.target.value } })} /></Field>
        <Field span label={L('Street address', 'Adresse')} id="ob-a" error={errs.address}><input id="ob-a" className="input" value={r.address} onChange={(e) => upd({ r: { ...r, address: e.target.value } })} /></Field>
        <Field label={L('Phone', 'Téléphone')} id="ob-p" error={errs.phone} hint={L('10 digits', '10 chiffres')}><input id="ob-p" className="input" inputMode="tel" value={r.phone} onChange={(e) => upd({ r: { ...r, phone: e.target.value } })} /></Field>
        <Field label={L('Number of seats', 'Nombre de places')} id="ob-s" error={errs.seats}><input id="ob-s" className="input" type="number" min="0" value={r.seats} onChange={(e) => upd({ r: { ...r, seats: e.target.value } })} /></Field>
      </div>
      <div className="dr-label">{L('Type of restaurant', 'Type de restaurant')}</div>
      <div className="ob-opts three">{[['quick', 'hamburger', L('Counter service', 'Comptoir')], ['casual', 'fork-knife', L('Casual dining', 'Restaurant familial')], ['fine', 'wine', L('Fine dining', 'Gastronomique')]].map(([k, ic, t]) => opt(r.kind === k, ic, t, null, () => upd({ r: { ...r, kind: k } })))}</div>
    </>,
    inventory: <>
      <p className="ob-lede">{L('If you already keep your stock in Excel, bring it in — MIZO matches the columns for you. No spreadsheet? Start with our sample list and change it later.', 'Si votre stock est dans Excel, importez-le — MIZO associe les colonnes. Pas de fichier? Partez de notre liste d’exemple.')}</p>
      <div className="ob-opts">
        {opt(S.inv === 'excel', 'microsoft-excel-logo', L('Import my Excel file', 'Importer mon fichier Excel'), L('.xlsx, .xls or .csv — takes about 2 minutes', '.xlsx, .xls ou .csv — environ 2 minutes'), () => { upd({ inv: 'excel' }); openImport('inventory'); })}
        {opt(S.inv === 'sample', 'list-checks', L('Use the sample Greek restaurant list', 'Utiliser la liste d’exemple'), L(`${c.inv.length} ingredients with prices — edit any time`, `${c.inv.length} ingrédients avec prix — modifiable`), () => upd({ inv: 'sample' }))}
        {opt(false, 'download-simple', L('Download a blank template', 'Télécharger un modèle vide'), L('Fill it in, then come back and import it', 'Remplissez-le, puis importez-le'), tpl)}
      </div>
    </>,
    suppliers: <>
      <p className="ob-lede">{L('Who you buy from. MIZO uses this to send orders and compare prices.', 'Vos fournisseurs. MIZO s’en sert pour commander et comparer les prix.')}</p>
      <div className="ob-sups">{[...D.suppliers.map((s) => ({ name: s.name, email: s.contact, phone: s.phone, base: true })), ...S.sups].map((s, j) => <div key={j} className="ob-sup"><span className="alert-ic acc"><Icon n="truck" /></span><div><b>{s.name}</b><div className="muted sm">{s.email}{s.phone ? ' · ' + s.phone : ''}</div></div>{s.base ? <span className="tag tag-neutral">{L('From sample', 'Exemple')}</span> : <Pill tone="pos">{L('Added', 'Ajouté')}</Pill>}</div>)}</div>
      <div className="ob-add">
        <div className="dr-label">{L('Add a supplier', 'Ajouter un fournisseur')}</div>
        <div className="form-grid">
          <Field span label={L('Company name', 'Nom de l’entreprise')} id="ob-sn" error={errs.sname}><input id="ob-sn" className="input" value={sup.name} onChange={(e) => setSup({ ...sup, name: e.target.value })} placeholder="Fromagerie Hamel" /></Field>
          <Field label={L('Order email', 'Courriel des commandes')} id="ob-se" error={errs.semail} hint={L('Optional', 'Facultatif')}><input id="ob-se" className="input" type="email" value={sup.email} onChange={(e) => setSup({ ...sup, email: e.target.value })} /></Field>
          <Field label={L('Phone', 'Téléphone')} id="ob-sp" error={errs.sphone} hint={L('Optional', 'Facultatif')}><input id="ob-sp" className="input" inputMode="tel" value={sup.phone} onChange={(e) => setSup({ ...sup, phone: e.target.value })} /></Field>
        </div>
        <div><button className="btn btn-secondary" onClick={addSup}><Icon n="plus" />{L('Add supplier', 'Ajouter')}</button></div>
      </div>
    </>,
    recipes: <>
      <p className="ob-lede">{L('Recipes let MIZO work out what each dish costs to make. Start from common dishes and adjust the amounts to match your kitchen.', 'Les recettes permettent de calculer le coût de chaque plat. Partez de plats courants et ajustez.')}</p>
      <div className="ob-opts">
        {opt(S.rec === 'tpl', 'cooking-pot', L('Start from Greek restaurant recipes', 'Partir de recettes de restaurant grec'), L(`${recipes.length} dishes: pitas, plates, salads, sides, desserts`, `${recipes.length} plats : pitas, assiettes, salades, accomp., desserts`), () => upd({ rec: 'tpl' }))}
        {opt(S.rec === 'excel', 'microsoft-excel-logo', L('Import recipes from Excel', 'Importer depuis Excel'), null, () => { upd({ rec: 'excel' }); openImport('recipes'); })}
        {opt(S.rec === 'later', 'clock', L('I’ll add them later', 'Plus tard'), L('Food cost per dish will show once recipes are in', 'Le coût par plat s’affichera ensuite'), () => upd({ rec: 'later' }))}
      </div>
    </>,
    target: <>
      <p className="ob-lede">{L('What share of a dish’s price should go to ingredients? Dishes above this are flagged so you can adjust the price or portion.', 'Quelle part du prix d’un plat va aux ingrédients? Les plats au-dessus sont signalés.')}</p>
      <div className="ob-target"><b className="tnum">{target}%</b><input type="range" className="range" min="22" max="38" step="1" value={target} onChange={(e) => setTarget(Number(e.target.value))} aria-label={L('Food cost target', 'Cible de coût alimentaire')} /><div className="ob-scale muted sm"><span>22%</span><span>{L('Most restaurants: 28–32%', 'La plupart : 28–32 %')}</span><span>38%</span></div></div>
      {ex ? <div className="suggest"><Icon n="lightbulb" /><div>{L(`Example: your ${ex.name.en.toLowerCase()} sells for ${fmt.money(ex.price)}. At ${target}%, its ingredients should cost about ${fmt.money((ex.price * target) / 100)}.`, `Exemple : votre ${ex.name.fr.toLowerCase()} se vend ${fmt.money(ex.price)}. À ${target} %, les ingrédients devraient coûter environ ${fmt.money((ex.price * target) / 100)}.`)}</div></div> : null}
    </>,
    pos: <>
      <p className="ob-lede">{L('Connecting your till brings in sales automatically. The live connection comes in a later release — for now, tell us what you use and we’ll get you ready.', 'La connexion de la caisse importe les ventes automatiquement. Elle arrive dans une prochaine version — dites-nous ce que vous utilisez.')}</p>
      <div className="ob-opts three">{POS_LIST.map(([k, n]) => opt(S.pos === k, 'cash-register', n || L('Other / not sure', 'Autre / je ne sais pas'), null, () => upd({ pos: k })))}</div>
      {S.pos ? <div className="ob-ready"><div className="dr-label">{L('What you’ll need on connection day', 'Ce qu’il faudra le jour de la connexion')}</div><ul className="ob-check">{[L('The owner or admin login for your POS', 'L’accès administrateur de votre PDV'), L('About 15 minutes', 'Environ 15 minutes'), L('Your menu items in the POS — MIZO matches them to your recipes', 'Vos articles dans le PDV — MIZO les associe aux recettes')].map((t, j) => <li key={j}><Icon n="check-circle" />{t}</li>)}</ul><button className="btn btn-secondary" onClick={() => setMail(true)}><Icon n="envelope-simple" />{L('Email me these instructions', 'M’envoyer les instructions')}</button></div> : null}
    </>,
    explore: <>
      <p className="ob-lede">{L('You’re set up. Here’s what MIZO knows so far — you can change any of it in Settings.', 'C’est prêt. Voici ce que MIZO sait — tout est modifiable dans les paramètres.')}</p>
      <ul className="ob-sum">{SETUP_STEPS.slice(0, -1).map(([k, ic, t]) => <li key={k}><Icon n={S.done[k] ? 'check-circle' : 'circle-dashed'} className={S.done[k] ? 'txt-pos' : 'muted'} /><span>{L(...t)}</span><span className="muted">{S.done[k] ? L('Done', 'Fait') : L('Skipped — you can finish it later', 'Passé — à terminer plus tard')}</span></li>)}</ul>
      <div className="ob-opts two">{opt(false, 'compass', L('Take the 2-minute tour', 'Faire la visite de 2 minutes'), L('See where everything is', 'Voir où tout se trouve'), () => { setSetup({ ...S, done: { ...S.done, explore: true } }); onClose(); onTour(); })}{opt(false, 'squares-four', L('Go to my dashboard', 'Aller au tableau de bord'), null, () => { setSetup({ ...S, done: { ...S.done, explore: true } }); onClose(); })}</div>
    </>,
  }[key];
  return ReactDOM.createPortal(
    <div className="ob" role="dialog" aria-modal="true" aria-labelledby="ob-title">
      <div className="ob-card">
        <aside className="ob-side">
          <div className="ob-brand"><span className="logo ob-logo"></span><div><b>MIZO</b><div className="muted sm">{L('Setup guide', 'Guide de configuration')}</div></div></div>
          <ol className="ob-steps">{SETUP_STEPS.map(([k, ic, t], j) => <li key={k}><button className={(j === i ? 'on' : '') + (S.done[k] ? ' done' : '')} onClick={() => { setErrs({}); upd({ step: j }); }} aria-current={j === i ? 'step' : undefined}><span className="ob-n">{S.done[k] ? <Icon n="check" /> : j + 1}</span>{L(...t)}</button></li>)}</ol>
          <div className="ob-prog"><div className="muted sm">{L(`${nDone} of ${SETUP_STEPS.length} done`, `${nDone} sur ${SETUP_STEPS.length} terminées`)}</div><span className="budbar"><span className="budbar-fill" style={{ width: (nDone / SETUP_STEPS.length) * 100 + '%' }}></span></span></div>
        </aside>
        <section className="ob-main">
          <div className="ob-top"><span className="muted">{L(`Step ${i + 1} of ${SETUP_STEPS.length}`, `Étape ${i + 1} sur ${SETUP_STEPS.length}`)}</span><button className="btn btn-ghost" onClick={onClose}>{L('Finish later', 'Terminer plus tard')}<Icon n="x" /></button></div>
          <div className="ob-body" key={key}>
            <span className="ob-ic"><Icon n={SETUP_STEPS[i][1]} /></span>
            <h1 id="ob-title">{i === 0 && !S.seen ? L('Welcome to MIZO', 'Bienvenue dans MIZO') : L(...SETUP_STEPS[i][2])}</h1>
            {body}
          </div>
          <div className="ob-foot">
            {i > 0 ? <button className="btn btn-secondary" onClick={() => { setErrs({}); upd({ step: i - 1 }); }}><Icon n="arrow-left" />{L('Back', 'Retour')}</button> : <span></span>}
            <span style={{ flex: 1 }}></span>
            {key !== 'explore' && key !== 'lang' ? <button className="btn btn-ghost" onClick={() => { setErrs({}); upd({ step: i + 1 }); }}>{L('Skip for now', 'Passer')}</button> : null}
            <button className="btn btn-primary ob-next" onClick={next}>{key === 'explore' ? L('Finish setup', 'Terminer') : L('Save and continue', 'Enregistrer et continuer')}<Icon n={key === 'explore' ? 'check' : 'arrow-right'} /></button>
          </div>
        </section>
      </div>
      <SimSendModal open={mail} onClose={() => setMail(false)} title={L('Email the connection instructions', 'Envoyer les instructions')} to="eleni@souvlakivillage.ca" subject={L('Getting ready to connect your POS to MIZO', 'Préparer la connexion de votre PDV à MIZO')} lines={[L('Here’s what you’ll need on connection day:', 'Voici ce qu’il faudra le jour de la connexion :'), L('1. The owner or admin login for your POS', '1. L’accès administrateur de votre PDV'), L('2. About 15 minutes', '2. Environ 15 minutes'), L('3. Your menu items in the POS — MIZO matches them to your recipes', '3. Vos articles du PDV — MIZO les associe aux recettes')]} />
    </div>, document.body);
}

function SetupChecklist() {
  const { L, setup, setSetup, openSetup } = useMizo();
  if (setup.hide) return null;
  const n = SETUP_STEPS.filter(([k]) => setup.done[k]).length;
  if (n === SETUP_STEPS.length) return null;
  const nextI = SETUP_STEPS.findIndex(([k]) => !setup.done[k]);
  return (
    <section className="panel setup-card">
      <div className="setup-top">
        <div><div className="ai-kicker"><Icon n="list-checks" />{L('Getting started', 'Pour commencer')}</div><h3>{L(`${n} of ${SETUP_STEPS.length} setup steps done`, `${n} étapes sur ${SETUP_STEPS.length} terminées`)}</h3></div>
        <div className="itools"><button className="btn btn-primary" onClick={() => openSetup(nextI)}>{L('Continue setup', 'Continuer')}<Icon n="arrow-right" /></button><button className="btn btn-ghost btn-icon" onClick={() => setSetup({ ...setup, hide: true })} aria-label={L('Hide', 'Masquer')} title={L('Hide — reopen from Help', 'Masquer — rouvrir depuis l’Aide')}><Icon n="x" /></button></div>
      </div>
      <span className="budbar"><span className="budbar-fill" style={{ width: (n / SETUP_STEPS.length) * 100 + '%' }}></span></span>
      <ol className="setup-steps">{SETUP_STEPS.map(([k, ic, t], j) => <li key={k}><button className={setup.done[k] ? 'done' : ''} onClick={() => openSetup(j)}><Icon n={setup.done[k] ? 'check-circle' : ic} />{L(...t)}</button></li>)}</ol>
    </section>
  );
}

Object.assign(window, { SETUP_STEPS, SETUP0, SetupWizard, SetupChecklist });
