/* global React, ReactDOM, FINDER */
const { useState, useEffect, useMemo, useRef } = React;
const { FAMILIES, AGE_GROUPS, MOODS, GENDERS, OCCASIONS, SEASONS, PERFUMES, ALL_PERFUMES, ALLMAP, rank } = window.FINDER;

const INTENSITY_LABELS = ['', 'Jemná', 'Decentní', 'Vyvážená', 'Výrazná', 'Sálavá'];
const INTENSITY_DESCS  = ['', 'Skin-scent, sotva cítit', 'Milá stoupa na pár hodin', 'Dobrá výdrž, znát bez přepalu', 'Silná, táhne za sebou stopu', 'Sálá z dálky, celý den'];
const STORE_KEY = 'vp_finder_v2';

/* ============================================================
   STEP COMPONENTS
   ============================================================ */

function GenderStep({ a, set }) {
  const icons = { f: '♀', m: '♂', u: '⚥' };
  return (
    <div className="cards-3">
      {GENDERS.map(g => (
        <button key={g.id} type="button"
          className={'bigcard' + (a.gender === g.id ? ' is-active' : '')}
          onClick={() => set({ gender: g.id })}>
          <span className="bc-icon">{icons[g.id]}</span>
          <span className="bc-title">{g.label}</span>
          <span className="bc-sub">{g.sub}</span>
        </button>
      ))}
    </div>
  );
}

function OccasionStep({ a, set }) {
  const sel = a.occasions || [];
  const toggle = id => {
    if (sel.includes(id)) set({ occasions: sel.filter(x => x !== id) });
    else if (sel.length < 3) set({ occasions: [...sel, id] });
  };
  return (
    <div>
      <div className="tiles">
        {OCCASIONS.map(o => {
          const active = sel.includes(o.id);
          const disabled = !active && sel.length >= 3;
          return (
            <button key={o.id} type="button"
              className={'tile' + (active ? ' is-active' : '') + (disabled ? ' tile--off' : '')}
              onClick={() => toggle(o.id)}>
              <span className="tile-check">{active ? '✓' : ''}</span>
              <span className="tile-title">{o.label}</span>
              <span className="tile-sub">{o.sub}</span>
            </button>
          );
        })}
      </div>
      <p className="hint">{sel.length}/3 vybráno · zvolte až tři příležitosti.</p>
    </div>
  );
}

function FamilyStep({ a, set }) {
  const sel = a.families || [];
  const toggle = id => {
    if (sel.includes(id)) set({ families: sel.filter(x => x !== id) });
    else if (sel.length < 3) set({ families: [...sel, id] });
  };
  return (
    <div>
      <div className="fam-grid">
        {FAMILIES.map(f => {
          const active = sel.includes(f.id);
          const disabled = !active && sel.length >= 3;
          return (
            <button key={f.id} type="button"
              className={'fam' + (active ? ' is-active' : '') + (disabled ? ' is-disabled' : '')}
              onClick={() => toggle(f.id)}>
              <span className="fam-sw" style={{ background: f.sw }}></span>
              <span className="fam-text">
                <span className="fam-title">{f.label}</span>
                <span className="fam-sub">{f.sub}</span>
              </span>
              <span className="fam-dot">{active ? '✓' : ''}</span>
            </button>
          );
        })}
      </div>
      <p className="hint">{sel.length}/3 vybráno · zvolte jednu až tři rodiny.</p>
    </div>
  );
}

function AgeStep({ a, set }) {
  return (
    <div className="cards-4">
      {AGE_GROUPS.map(ag => (
        <button key={ag.id} type="button"
          className={'agecard' + (a.ageGroup === ag.id ? ' is-active' : '')}
          onClick={() => set({ ageGroup: ag.id })}>
          <span className="ac-age">{ag.label}</span>
          <span className="ac-title">{ag.sub}</span>
          <span className="ac-desc">{ag.desc}</span>
        </button>
      ))}
    </div>
  );
}

function MoodStep({ a, set }) {
  const sel = a.moods || [];
  const toggle = id => {
    if (sel.includes(id)) set({ moods: sel.filter(x => x !== id) });
    else if (sel.length < 3) set({ moods: [...sel, id] });
  };
  return (
    <div>
      <div className="mood-wrap">
        {MOODS.map(m => (
          <button key={m.id} type="button"
            className={'chip' + (sel.includes(m.id) ? ' is-active' : '') + (!sel.includes(m.id) && sel.length >= 3 ? ' chip--off' : '')}
            onClick={() => toggle(m.id)}>
            {m.label}
          </button>
        ))}
      </div>
      <p className="hint">Vyberte až tři nálady — nebo přeskočte.</p>
    </div>
  );
}

function IntensityStep({ a, set }) {
  const v = a.intensity || 3;
  return (
    <div className="slider-block">
      <div className="int-cards">
        {[1,2,3,4,5].map(n => (
          <button key={n} type="button"
            className={'int-card' + (v === n ? ' is-active' : '')}
            onClick={() => set({ intensity: n })}>
            <span className="int-num">{n}</span>
            <span className="int-lbl">{INTENSITY_LABELS[n]}</span>
            <span className="int-desc">{INTENSITY_DESCS[n]}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

function SeasonStep({ a, set }) {
  const sel = a.seasons || [];
  const toggle = id => {
    if (sel.includes(id)) set({ seasons: sel.filter(x => x !== id) });
    else if (sel.length < 3) set({ seasons: [...sel, id] });
  };
  const icons = { jaro: '🌸', leto: '☀️', podzim: '🍂', zima: '❄️' };
  return (
    <div>
      <div className="season-grid">
        {SEASONS.map(s => {
          const active = sel.includes(s.id);
          const disabled = !active && sel.length >= 3;
          return (
            <button key={s.id} type="button"
              className={'season-card' + (active ? ' is-active' : '') + (disabled ? ' is-disabled' : '')}
              onClick={() => toggle(s.id)}>
              <span className="sc-icon">{icons[s.id]}</span>
              <span className="sc-title">{s.label}</span>
              <span className="sc-sub">{s.sub}</span>
              <span className="sc-check">{active ? '✓' : ''}</span>
            </button>
          );
        })}
      </div>
      <p className="hint">{sel.length}/3 vybráno · vyberte jedno až tři roční období.</p>
    </div>
  );
}

function BudgetStep({ a, set }) {
  const v = a.budget || 200;
  const tiers = [
    { max: 99,  label: 'Do 99 Kč',  desc: 'Skvělý poměr, arabské a designérské vůně' },
    { max: 149, label: 'Do 149 Kč', desc: 'Větší výběr, niche i bestsellery' },
    { max: 199, label: 'Do 199 Kč', desc: 'Prémiový výběr a niche značky' },
    { max: 999, label: 'Bez limitu', desc: 'Vše včetně luxury a rarit' },
  ];
  const count = PERFUMES.filter(p => p.price <= v).length;
  return (
    <div className="budget-block">
      <div className="budget-tiers">
        {tiers.map(t => (
          <button key={t.max} type="button"
            className={'budget-tier' + (v === t.max ? ' is-active' : '')}
            onClick={() => set({ budget: t.max })}>
            <span className="bt-label">{t.label}</span>
            <span className="bt-desc">{t.desc}</span>
            <span className="bt-count">{PERFUMES.filter(p => p.price <= t.max).length} vzorků</span>
          </button>
        ))}
      </div>
      <p className="hint">{count} vůní v tomto rozpočtu · vzorky od 69 Kč</p>
    </div>
  );
}

function FavoritesStep({ a, set }) {
  const sel = a.favorites || [];
  const [q, setQ] = useState('');
  const toggle = id => {
    if (sel.includes(id)) set({ favorites: sel.filter(x => x !== id) });
    else if (sel.length < 5) set({ favorites: [...sel, id] });
  };
  const query = q.trim().toLowerCase();
  const results = ALL_PERFUMES.filter(p =>
    !query || (p.brand + ' ' + p.name).toLowerCase().includes(query)
  ).slice(0, 60);
  return (
    <div className="fav-block">
      <p className="ref-lede">Zohledníme vonné rodiny vašich oblíbených. Tenhle krok je nepovinný.</p>

      {sel.length > 0 && (
        <div className="fav-selected">
          {sel.map(id => {
            const p = ALLMAP[id];
            if (!p) return null;
            return (
              <button key={id} type="button" className="fav-chip" onClick={() => toggle(id)}>
                <span>{p.brand} <b>{p.name}</b></span><span className="x">✕</span>
              </button>
            );
          })}
        </div>
      )}

      <div className="fav-search">
        <span className="fav-ico">⌕</span>
        <input value={q} onChange={e => setQ(e.target.value)} placeholder="Hledat parfém nebo značku…" />
        <span className="fav-count">{sel.length}/5</span>
      </div>

      <div className="fav-results">
        {results.map(p => {
          const active = sel.includes(p.id);
          const disabled = !active && sel.length >= 5;
          return (
            <button key={p.id} type="button"
              className={'fav-item' + (active ? ' is-active' : '') + (disabled ? ' is-disabled' : '')}
              onClick={() => toggle(p.id)}>
              {p.img && (
                <span className="fav-thumb" style={{ backgroundImage: `url(${p.img})` }} aria-hidden="true" />
              )}
              <span className="fav-meta"><span className="fav-b">{p.brand}</span><span className="fav-n">{p.name}</span></span>
              <span className="fav-add">{active ? '✓' : '+'}</span>
            </button>
          );
        })}
        {results.length === 0 && <p className="hint" style={{ gridColumn: '1 / -1' }}>Nic jsme nenašli — zkuste jiný název.</p>}
      </div>
    </div>
  );
}

/* ============================================================
   SUMMARY RAIL
   ============================================================ */
function SummaryRail({ a }) {
  const g = GENDERS.find(x => x.id === a.gender);
  const occ = (a.occasions || []).map(id => OCCASIONS.find(o => o.id === id)?.label).filter(Boolean);
  const fam = (a.families || []).map(id => FAMILIES.find(f => f.id === id)?.label).filter(Boolean);
  const mood = (a.moods || []).map(id => MOODS.find(m => m.id === id)?.label).filter(Boolean);
  const seasons = (a.seasons || []).map(id => SEASONS.find(s => s.id === id)?.label).filter(Boolean);
  const ag = AGE_GROUPS.find(x => x.id === a.ageGroup);
  const favs = (a.favorites || []).map(id => ALLMAP[id]?.name).filter(Boolean);

  const Row = ({ label, value }) => (
    <div className={'sum-row' + (value && value.length ? ' filled' : '')}>
      <span className="sum-k">{label}</span>
      <span className="sum-v">{value && value.length ? value : '—'}</span>
    </div>
  );

  return (
    <aside className="rail">
      <div className="rail-head">
        <span className="eyebrow">Váš profil</span>
        <p>Shrnutí odpovědí</p>
      </div>
      <div className="sum">
        <Row label="Pro koho"    value={g ? g.label : ''} />
        <Row label="Příležitost" value={occ.join(', ')} />
        <Row label="Vůně"        value={fam.join(', ')} />
        <Row label="Věk"         value={ag ? ag.label : ''} />
        <Row label="Charakter"   value={mood.join(', ')} />
        <Row label="Intenzita"   value={a.intensity ? INTENSITY_LABELS[a.intensity] : ''} />
        <Row label="Období"      value={seasons.join(', ')} />
        <Row label="Rozpočet"    value={a.budget ? ('do ' + a.budget + ' Kč') : ''} />
        <Row label="Oblíbené"    value={favs.join(', ')} />
      </div>
      <div className="rail-foot">
        <div className="vial" aria-hidden="true"><span style={{ height: '42%' }}></span></div>
        <p>2 ml vzorek · vydrží 5–10 dní</p>
      </div>
    </aside>
  );
}

/* ============================================================
   COMPUTING
   ============================================================ */
const COMP_DURATION = 10000;
const COMP_STEPS = [
  'Analyzuji vaše preference…',
  'Procházím 504 vzorků z katalogu…',
  'Porovnávám vonné rodiny a noty…',
  'Vyhodnocuji příležitosti a sezónu…',
  'Zohledňuji věk a intenzitu…',
  'Matchuji s oblíbenými parfémy…',
  'Řadím výsledky podle shody…',
  'Připravuji vaše doporučení…',
];

function Computing({ onDone }) {
  const [stepIdx, setStepIdx] = useState(0);
  const [pct, setPct] = useState(0);

  useEffect(() => {
    const start = Date.now();
    const tick = setInterval(() => {
      const elapsed = Date.now() - start;
      const raw = elapsed / COMP_DURATION;
      // ease-out: fast at first, slow near end
      const eased = 1 - Math.pow(1 - Math.min(raw, 0.99), 2);
      setPct(Math.min(eased * 100, 99));
      const idx = Math.min(Math.floor(raw * COMP_STEPS.length), COMP_STEPS.length - 1);
      setStepIdx(idx);
    }, 80);
    const done = setTimeout(() => { setPct(100); setTimeout(onDone, 300); }, COMP_DURATION);
    return () => { clearInterval(tick); clearTimeout(done); };
  }, []);

  return (
    <div className="computing">
      <div className="ring"></div>
      <h2>Hledám vaši vůni</h2>
      <p className="comp-line" key={stepIdx}>{COMP_STEPS[stepIdx]}</p>
      <div className="comp-bar-wrap">
        <div className="comp-bar" style={{ width: pct + '%' }}></div>
      </div>
      <span className="comp-pct">{Math.round(pct)} %</span>
    </div>
  );
}

/* ============================================================
   RESULT
   ============================================================ */
function BlurbModal({ perfume, onClose }) {
  useEffect(() => {
    const h = e => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, []);
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal-box" onClick={e => e.stopPropagation()}>
        <button className="modal-close" onClick={onClose} type="button">✕</button>
        {perfume.img && <img src={perfume.img} alt={perfume.brand + ' ' + perfume.name} className="modal-img" />}
        <div className="modal-body">
          <span className="modal-brand">{perfume.brand}</span>
          <h3 className="modal-name">{perfume.name}</h3>
          <p className="modal-desc">{perfume.blurb || 'Popis není k dispozici.'}</p>
          {(perfume.notes?.top || perfume.notes?.heart || perfume.notes?.base) && (
            <div className="modal-notes">
              {perfume.notes.top   && <div><span>Hlava</span><b>{perfume.notes.top}</b></div>}
              {perfume.notes.heart && <div><span>Srdce</span><b>{perfume.notes.heart}</b></div>}
              {perfume.notes.base  && <div><span>Základ</span><b>{perfume.notes.base}</b></div>}
            </div>
          )}
          <a className="btn btn--solid modal-btn" href={perfume.url} target="_blank" rel="noopener">
            Objednat vzorek na MrRizz <span className="arr">↗</span>
          </a>
        </div>
      </div>
    </div>
  );
}

function Result({ ranked, a, onRestart, onEdit }) {
  const [modal, setModal] = useState(null);
  const top = ranked[0];
  const alts = ranked.slice(1, 7);
  const p = top.perfume;

  return (
    <div className="result">
      {modal && <BlurbModal perfume={modal} onClose={() => setModal(null)} />}

      <div className="result-head">
        <span className="eyebrow">Vaše shoda — na míru</span>
        <h1>Tohle je <em>vaše vůně.</em></h1>
      </div>

      <div className="match-card">
        <div className="mc-art">
          {p.img
            ? <img src={p.img} alt={p.brand + ' ' + p.name} className="mc-img" />
            : <div className="mc-img-ph">{p.brand[0]}</div>
          }
          <span className="mc-match"><b>{top.match}%</b> shoda</span>
        </div>
        <div className="mc-body">
          <div className="mc-head-row">
            <div>
              <span className="mc-brand">{p.brand}</span>
              <h2 className="mc-name">{p.name}</h2>
            </div>
            <div className="mc-price-block">
              <span className="mc-price-label">vzorek 2 ml</span>
              <span className="mc-price-val">{p.price} Kč</span>
            </div>
          </div>

          {p.blurb && (
            <p className="mc-blurb">
              {p.blurb.length > 120 ? p.blurb.slice(0, 120) + '…' : p.blurb}
              {p.blurb.length > 120 && (
                <button className="mc-more" type="button" onClick={() => setModal(p)}>číst více</button>
              )}
            </p>
          )}

          {(p.notes?.top || p.notes?.heart || p.notes?.base) && (
            <div className="mc-notes">
              <div><span>Hlava</span><b>{p.notes.top || '—'}</b></div>
              <div><span>Srdce</span><b>{p.notes.heart || '—'}</b></div>
              <div><span>Základ</span><b>{p.notes.base || '—'}</b></div>
            </div>
          )}

          {top.reasons.length > 0 && (
            <div className="mc-why">
              <span className="mc-why-k">Proč právě tahle:</span>
              <div className="mc-why-chips">{top.reasons.map((r, i) => <span key={i}>{r}</span>)}</div>
            </div>
          )}

          <div className="mc-actions">
            <a className="btn btn--solid" href={p.url} target="_blank" rel="noopener">
              Objednat vzorek <span className="arr">↗</span>
            </a>
            {p.blurb && (
              <button className="btn btn--ghost" type="button" onClick={() => setModal(p)}>
                Více o vůni
              </button>
            )}
          </div>
        </div>
      </div>

      <div className="alts">
        <div className="alts-head"><span className="eyebrow">Mohlo by sednout i tohle</span></div>
        <div className="alts-grid">
          {alts.map(s => {
            const ap = s.perfume;
            const fam = FAMILIES.find(f => f.id === (ap.families||[])[0]);
            return (
              <div key={ap.id} className="alt" onClick={() => setModal(ap)} role="button" tabIndex={0}>
                <div className="alt-img-wrap">
                  {ap.img
                    ? <img src={ap.img} alt={ap.brand + ' ' + ap.name} className="alt-img" />
                    : <div className="alt-img-ph">{ap.brand[0]}</div>
                  }
                  <span className="alt-match-badge">{s.match}%</span>
                </div>
                <div className="alt-info">
                  <span className="alt-fam" style={{ color: fam ? fam.sw : '#999' }}>{fam ? fam.label : ''}</span>
                  <span className="alt-brand">{ap.brand}</span>
                  <span className="alt-name">{ap.name}</span>
                  <div className="alt-foot">
                    <span>{ap.price} Kč</span>
                    <a href={ap.url} target="_blank" rel="noopener" onClick={e => e.stopPropagation()} className="alt-buy">
                      Vzorek <span className="arr">↗</span>
                    </a>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      <div className="result-actions">
        <button className="btn btn--ghost" onClick={onEdit} type="button">Upravit odpovědi</button>
        <button className="link-btn" onClick={onRestart} type="button">Začít znovu</button>
        <a className="link-btn" href="https://mrrizz.cz" target="_blank" rel="noopener">Všechny vůně na MrRizz ↗</a>
      </div>
    </div>
  );
}

/* ============================================================
   STEP CONFIG
   ============================================================ */
const STEPS = [
  { key: 'gender',  eyebrow: '01', q: 'Pro koho hledáme?',          help: 'Zvolte gender — nezávazně, vůně nemají pohlaví.',      comp: GenderStep,    valid: a => !!a.gender },
  { key: 'occ',     eyebrow: '02', q: 'Kdy ji budete nosit?',        help: 'Vyberte až tři příležitosti.',                         comp: OccasionStep,  valid: a => (a.occasions||[]).length > 0 },
  { key: 'fam',     eyebrow: '03', q: 'Jaké druhy vůní vás táhnou?', help: 'Vonné rodiny — zvolte jednu až tři.',                  comp: FamilyStep,    valid: a => (a.families||[]).length > 0 },
  { key: 'age',     eyebrow: '04', q: 'Pro jakou věkovou skupinu?',  help: 'Pomůže zpřesnit styl a charakter vůně.',               comp: AgeStep,       valid: a => !!a.ageGroup },
  { key: 'mood',    eyebrow: '05', q: 'Jaký charakter má mít?',      help: 'Nálada a osobnost vůně — nebo přeskočte.',             comp: MoodStep,      valid: () => true },
  { key: 'int',     eyebrow: '06', q: 'Jak silná má být?',           help: 'Od skin-scentu po sálající stopu.',                    comp: IntensityStep, valid: () => true },
  { key: 'season',  eyebrow: '07', q: 'Na jaké roční období?',       help: 'Vůně se liší v horkém a chladném počasí — až tři.',   comp: SeasonStep,    valid: a => (a.seasons||[]).length > 0 },
  { key: 'budget',  eyebrow: '08', q: 'Jaký je váš rozpočet?',       help: 'Cena za 2 ml vzorek.',                                 comp: BudgetStep,    valid: () => true },
  { key: 'ref',     eyebrow: '09', q: 'Máte oblíbené parfémy?',      help: 'Přidejte až 5 — zpřesní doporučení. Nepovinné.',      comp: FavoritesStep, valid: () => true },
];

const TOTAL = STEPS.length;

/* ============================================================
   APP
   ============================================================ */
function App() {
  const [phase, setPhase] = useState('intro');
  const [step, setStep] = useState(0);
  const [a, setA] = useState({ intensity: 3, budget: 199, occasions: [], families: [], moods: [], seasons: [], favorites: [] });
  const [dir, setDir] = useState(1);

  useEffect(() => {
    try {
      const raw = localStorage.getItem(STORE_KEY);
      if (raw) {
        const d = JSON.parse(raw);
        if (d.a) setA(prev => ({ ...prev, ...d.a }));
        if (d.phase) setPhase(d.phase);
        if (typeof d.step === 'number') setStep(d.step);
      }
    } catch (e) {}
  }, []);

  useEffect(() => {
    try { localStorage.setItem(STORE_KEY, JSON.stringify({ a, phase, step })); } catch (e) {}
  }, [a, phase, step]);

  const set = patch => setA(prev => ({ ...prev, ...patch }));
  const ranked = useMemo(() => (phase === 'result' ? rank(a) : null), [phase, a]);

  const cfg = STEPS[step];
  const canNext = cfg ? cfg.valid(a) : false;
  const progress = ((step + (phase === 'result' || phase === 'computing' ? 1 : 0)) / TOTAL) * 100;

  function next() {
    if (!canNext) return;
    if (step < TOTAL - 1) { setDir(1); setStep(step + 1); }
    else { setPhase('computing'); }
  }
  function back() {
    if (step > 0) { setDir(-1); setStep(step - 1); }
    else { setPhase('intro'); }
  }
  function restart() {
    setA({ intensity: 3, budget: 199, occasions: [], families: [], moods: [], seasons: [], favorites: [] });
    setStep(0); setPhase('intro');
    try { localStorage.removeItem(STORE_KEY); } catch(e) {}
  }

  useEffect(() => {
    const h = e => {
      if (phase !== 'steps') return;
      if (e.key === 'Enter' && canNext) next();
      if (e.key === 'ArrowLeft') back();
    };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [phase, step, canNext, a]);

  /* INTRO */
  if (phase === 'intro') {
    return (
      <div className="screen intro-screen">
        <a className="exit" href="/">✕ Zavřít</a>
        <div className="intro-inner">
          <span className="eyebrow">Hledač parfémů · VzorkyParfemu.cz</span>
          <h1>Najdeme vám parfém<br /><em>na míru.</em></h1>
          <p className="intro-lede">Devět rychlých otázek. Z více než 500 parfémů vybereme ten, který sedne vašemu stylu, věku, příležitosti i ročnímu období.</p>
          <button className="btn btn--solid lg" onClick={() => { setPhase('steps'); setStep(0); }} type="button">
            Spustit hledač <span className="arr">→</span>
          </button>
          <div className="intro-meta">
            <span>≈ 90 sekund</span><span className="sep">·</span><span>zdarma</span><span className="sep">·</span><span>vzorky od 69 Kč</span>
          </div>
        </div>
      </div>
    );
  }

  /* COMPUTING */
  if (phase === 'computing') {
    return (
      <div className="screen dark-screen">
        <Computing onDone={() => setPhase('result')} />
      </div>
    );
  }

  /* RESULT */
  if (phase === 'result') {
    return (
      <div className="screen result-screen">
        <div className="topbar">
          <a className="brand" href="/">Vzorky<span className="dot">·</span>Parfemu</a>
          <a className="exit" href="/">✕ Zavřít</a>
        </div>
        <div className="result-scroll">
          <Result ranked={ranked} a={a} onRestart={restart} onEdit={() => { setPhase('steps'); setStep(0); }} />
        </div>
      </div>
    );
  }

  /* STEPS */
  const StepComp = cfg.comp;
  return (
    <div className="screen steps-screen">
      <div className="topbar">
        <a className="brand" href="/">Vzorky<span className="dot">·</span>Parfemu</a>
        <div className="progress"><span style={{ width: progress + '%' }}></span></div>
        <span className="step-counter">{step + 1}/{TOTAL}</span>
        <a className="exit" href="/">✕ Zavřít</a>
      </div>

      <div className="stage">
        <SummaryRail a={a} />

        <main className="canvas">
          <div className={'step ' + (dir > 0 ? 'in-right' : 'in-left')} key={cfg.key}>
            <div className="step-head">
              <span className="eyebrow step-eyebrow">Otázka {cfg.eyebrow} <span className="of">/ {String(TOTAL).padStart(2,'0')}</span></span>
              <h2>{cfg.q}</h2>
              <p className="step-help">{cfg.help}</p>
            </div>
            <div className="step-body">
              <StepComp a={a} set={set} />
            </div>
          </div>
        </main>
      </div>

      <div className="navbar">
        <button className="nav-back" onClick={back} type="button">← Zpět</button>
        <div className="dots">
          {STEPS.map((s, i) => <span key={i} className={i === step ? 'on' : (i < step ? 'done' : '')}></span>)}
        </div>
        <button className={'nav-next' + (canNext ? '' : ' is-off')} onClick={next} disabled={!canNext} type="button">
          {step === TOTAL - 1 ? 'Zobrazit výsledek' : 'Pokračovat'} <span className="arr">→</span>
        </button>
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('app')).render(<App />);
