const CEG = window.CertEngine;

function certGenUses(design, key) {
  return design.elements.some((el) => !el.hidden && ((el.type === 'field' && el.field === key) || (el.type === 'text' && String(el.text || '').indexOf('{' + key + '}') !== -1)));
}

function CertGenThumb({ design, data, flagged, onOpen }) {
  const [src, setSrc] = React.useState(null);
  const ref = React.useRef(null);
  const key = JSON.stringify(data);
  React.useEffect(() => {
    let alive = true, done = false;
    const go = () => { if (done) return; done = true; CEG.renderToCanvas(design, data, 240 / design.page.w).then((c) => { if (alive) setSrc(c.toDataURL('image/jpeg', 0.82)); }); };
    const io = new IntersectionObserver((es) => { if (es.some((e) => e.isIntersecting)) { go(); io.disconnect(); } }, { rootMargin: '200px' });
    if (ref.current) io.observe(ref.current);
    return () => { alive = false; io.disconnect(); };
  }, [key]);
  return (
    <button ref={ref} type="button" onClick={onOpen} title="Click to view larger" style={{ display: 'block', width: '100%', padding: 0, border: '1.5px solid ' + (flagged ? 'var(--status-warning, #D98E04)' : 'var(--border-default)'), borderRadius: 8, overflow: 'hidden', background: 'var(--bg-sunken)', cursor: 'zoom-in', aspectRatio: design.page.w + ' / ' + design.page.h }}>
      {src ? <img src={src} alt="" style={{ width: '100%', height: '100%', objectFit: 'contain', display: 'block' }} /> : <div className="ud-skel" style={{ width: '100%', height: '100%', borderRadius: 0 }}></div>}
    </button>
  );
}

function CertGenerateDialog({ tpl, initialVersion, initialSubId, reprint, adminName, onClose, onDone }) {
  const { Button } = window.TheUpperDeckDesignSystem_4d3294;
  const CertModal = window.CertModal;
  const latest = tpl.versions[tpl.versions.length - 1].n;
  const [step, setStep] = React.useState('setup');
  const [versionN, setVersionN] = React.useState(initialVersion || latest);
  const [mainEvents, setMainEvents] = React.useState(null);
  const [subId, setSubId] = React.useState('');
  const [atts, setAtts] = React.useState(null);
  const [scope, setScope] = React.useState('checked');
  const [includeRefunded, setIncludeRefunded] = React.useState(false);
  const [picked, setPicked] = React.useState({});
  const [sortBy, setSortBy] = React.useState('last');
  const [hours, setHours] = React.useState('');
  const [note, setNote] = React.useState('');
  const [output, setOutput] = React.useState('zip');
  const [perSheet, setPerSheet] = React.useState(1);
  const [sheet, setSheet] = React.useState('a4');
  const [fixes, setFixesRaw] = React.useState(() => CEG.loadNameFixes());
  const setFixes = (fn) => setFixesRaw((prev) => {
    const next = typeof fn === 'function' ? fn(prev) : fn;
    Object.keys(next).forEach((k) => { if (next[k] !== prev[k]) CEG.saveNameFix(k, next[k]); });
    Object.keys(prev).forEach((k) => { if (!(k in next)) CEG.saveNameFix(k, null); });
    return next;
  });
  const autoPicked = React.useRef(false);
  const [onlyFlagged, setOnlyFlagged] = React.useState(false);
  const [big, setBig] = React.useState(null);
  const [bigSrc, setBigSrc] = React.useState(null);
  const [progress, setProgress] = React.useState(null);
  const [error, setError] = React.useState('');

  const design = React.useMemo(() => CEG.versionDesign(tpl, versionN), [tpl, versionN]);
  const dType = CEG.docType(design), noun = CEG.DOC_TYPES[dType].plural, nounOne = CEG.DOC_TYPES[dType].label.toLowerCase();
  const [printed, setPrinted] = React.useState(() => CEG.loadPrinted());
  const [skipPrinted, setSkipPrinted] = React.useState(false);
  React.useEffect(() => { if (dType !== 'certificate') setPerSheet('fit'); }, [dType]);
  React.useEffect(() => { window.fetchMainEventsLive().then(setMainEvents).catch(() => setMainEvents([])); }, []);
  React.useEffect(() => { CEG.preload(design); }, [design]);
  React.useEffect(() => {
    if (!mainEvents || autoPicked.current || !initialSubId) return;
    autoPicked.current = true;
    if (!mainEvents.some((m) => m.subEvents.some((x) => x.id === initialSubId))) return;
    pickSub(initialSubId).then(() => { if (reprint) { setScope('pick'); setPicked({}); } });
  }, [mainEvents]);
  const subOpts = (mainEvents || []).flatMap((m) => m.subEvents.map((s) => ({ m, s })));
  const chosen = subOpts.find((o) => o.s.id === subId);
  const usesHours = certGenUses(design, 'hours'), usesNote = certGenUses(design, 'custom_note');

  async function pickSub(id) {
    setSubId(id); setAtts(null); setPicked({}); setError('');
    const o = subOpts.find((x) => x.s.id === id); setHours(o ? CEG.subHours(o.s) : '');
    if (!id) return;
    try { setAtts(await CEG.fetchAttendees(id)); } catch (e) { setAtts([]); setError('Could not load attendees for that sub-event.'); }
  }
  const base = (atts || []).filter((a) => a.orderStatus === 'paid' || (includeRefunded && a.orderStatus === 'refunded'));
  function switchScope(s) {
    if (s === 'pick' && scope !== 'pick') { const p = {}; (scope === 'checked' ? base.filter((a) => a.checkedIn) : base).forEach((a) => { p[a.ticketId] = true; }); setPicked(p); }
    setScope(s);
  }
  const chosenAtts0 = scope === 'checked' ? base.filter((a) => a.checkedIn) : scope === 'paid' ? base : base.filter((a) => picked[a.ticketId]);
  const chosenAtts = skipPrinted && scope !== 'pick' ? chosenAtts0.filter((a) => !printed[a.ticketId]) : chosenAtts0;
  const printedCount = chosenAtts0.filter((a) => printed[a.ticketId]).length;
  const pDate = (iso) => new Date(iso).toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
  const people = chosenAtts.map((a) => (fixes[a.ticketId] ? { ...a, ...fixes[a.ticketId] } : a));
  const sorted = people.slice().sort((a, b) => {
    if (sortBy === 'order') return a.certNumber.localeCompare(b.certNumber, undefined, { numeric: true });
    if (sortBy === 'first') return (a.first + ' ' + a.last).localeCompare(b.first + ' ' + b.last);
    return (a.last + ' ' + a.first).localeCompare(b.last + ' ' + b.first);
  });
  const extra = { hours: usesHours ? hours : undefined, note: usesNote ? note : undefined };
  const rows = React.useMemo(() => (step !== 'review' || !chosen) ? [] : sorted.map((a) => {
    const data = CEG.buildData(chosen.m, chosen.s, a, extra);
    const issues = [];
    if (!a.first) issues.push({ kind: 'missing', msg: 'First name is missing' });
    if (!a.last) issues.push({ kind: 'missing', msg: 'Last name is missing' });
    if (CEG.needsCase(a.first) || CEG.needsCase(a.last)) issues.push({ kind: 'case', msg: 'Name is ' + ((a.first + a.last) === (a.first + a.last).toLowerCase() ? 'all lowercase' : 'ALL CAPITALS') });
    CEG.checkData(design, data).forEach((i) => issues.push(i));
    return { a, data, issues };
  }), [step, chosen, JSON.stringify(sorted), design, hours, note]);
  const flaggedCount = rows.filter((r) => r.issues.length).length;
  const caseCount = rows.filter((r) => r.issues.some((i) => i.kind === 'case')).length;
  const shown = onlyFlagged ? rows.filter((r) => r.issues.length) : rows;

  function fixCase(a) { setFixes((f) => ({ ...f, [a.ticketId]: { first: CEG.titleCase(a.first), last: CEG.titleCase(a.last) } })); }
  function fixAllCase() { const n = { ...fixes }; rows.forEach((r) => { if (r.issues.some((i) => i.kind === 'case')) n[r.a.ticketId] = { first: CEG.titleCase(r.a.first), last: CEG.titleCase(r.a.last) }; }); setFixes(n); }
  function editName(a, k, v) { setFixes((f) => ({ ...f, [a.ticketId]: { first: (f[a.ticketId] || a).first, last: (f[a.ticketId] || a).last, [k]: v } })); }

  React.useEffect(() => {
    if (!big) { setBigSrc(null); return; }
    let alive = true; setBigSrc(null);
    CEG.renderToCanvas(design, big.data, 900 / design.page.w).then((c) => { if (alive) setBigSrc(c.toDataURL('image/jpeg', 0.9)); });
    return () => { alive = false; };
  }, [big]);

  async function run(mode) {
    setError('');
    try {
      const subSafe = CEG.safeName(chosen.s.title), used = {};
      const items = rows.map((r) => {
        let fn = subSafe + '_' + CEG.safeName(r.a.last) + '_' + CEG.safeName(r.a.first);
        if (used[fn]) { used[fn]++; fn += '-' + used[fn]; } else used[fn] = 1;
        return { data: r.data, filename: fn + '.pdf' };
      });
      const wantZip = mode === 'download' && (output === 'zip' || output === 'both');
      const wantPdf = mode === 'print' || (mode === 'download' && (output === 'pdf' || output === 'both'));
      const totalSteps = items.length * ((wantZip ? 1 : 0) + (wantPdf ? 1 : 0)); let done = 0;
      const tickP = () => { done++; setProgress({ done, total: totalSteps }); };
      setProgress({ done: 0, total: totalSteps });
      const layout = { perSheet, sheet };
      if (wantZip) { const zip = await CEG.buildZip(design, items, tickP); CEG.download(zip, subSafe + '_' + CEG.safeName(noun) + '.zip'); }
      if (wantPdf) {
        const pdf = await CEG.buildCombinedPdf(design, items.map((i) => i.data), tickP, layout);
        if (mode === 'print') CEG.printBlob(pdf); else CEG.download(pdf, subSafe + '_' + CEG.safeName(noun) + '.pdf');
      }
      const info = { at: new Date().toISOString(), by: adminName, tpl: tpl.name, how: mode === 'print' ? 'printed' : 'downloaded' };
      CEG.markPrinted(rows.map((r) => r.a.ticketId), info); setPrinted(CEG.loadPrinted());
      CEG.addHistory(tpl.id, { at: new Date().toISOString(), by: adminName, subEventTitle: chosen.s.title, subEventId: chosen.s.id, mainTitle: chosen.m.title, count: items.length, format: mode === 'print' ? 'print' : output, version: versionN, perSheet });
      setProgress(null);
      onDone(mode === 'print');
    } catch (e) { setError(e.message || 'Generation failed.'); setProgress(null); }
  }

  const radio = (v, label, hint) => (
    <button type="button" onClick={() => switchScope(v)} style={{ display: 'flex', gap: 10, alignItems: 'flex-start', padding: '10px 12px', border: '1.5px solid ' + (scope === v ? 'var(--brand-primary)' : 'var(--border-default)'), borderRadius: 'var(--radius-md)', cursor: 'pointer', background: scope === v ? 'color-mix(in srgb, var(--brand-primary) 6%, white)' : 'white', textAlign: 'left', fontFamily: 'var(--font-body)' }}>
      <span style={{ width: 16, height: 16, borderRadius: '50%', border: '2px solid ' + (scope === v ? 'var(--brand-primary)' : 'var(--border-strong, #b9c0c8)'), flexShrink: 0, marginTop: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{scope === v && <span style={{ width: 8, height: 8, borderRadius: '50%', background: 'var(--brand-primary)' }}></span>}</span>
      <span><span style={{ fontWeight: 600, fontSize: 'var(--text-sm)', color: 'var(--text-primary)' }}>{label}</span><br /><span style={{ fontSize: 'var(--text-xs)', color: 'var(--text-muted)' }}>{hint}</span></span>
    </button>
  );
  const pill = (on, onClick, label, key) => <button key={key || label} type="button" onClick={onClick} style={{ height: 34, padding: '0 14px', borderRadius: 'var(--radius-pill)', border: '1.5px solid ' + (on ? 'var(--navy-900)' : 'var(--border-default)'), background: on ? 'var(--navy-900)' : 'white', color: on ? 'white' : 'var(--navy-900)', fontSize: 'var(--text-sm)', fontWeight: 600, cursor: 'pointer', fontFamily: 'var(--font-body)' }}>{label}</button>;
  const lbl = { fontSize: 'var(--text-xs)', fontWeight: 700, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 8, display: 'block' };
  const inp = { width: '100%', boxSizing: 'border-box', height: 38, padding: '0 12px', borderRadius: 8, border: '1.5px solid var(--border-default)', fontSize: 'var(--text-sm)', fontFamily: 'var(--font-body)', outline: 'none' };
  const running = !!progress;
  const L = perSheet > 1 ? CEG.sheetLayout(design, perSheet, sheet) : null;

  const setupBody = (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,2fr) minmax(0,1fr)', gap: 12 }} className="ud-cert-gen-top">
        <div><span style={lbl}>Sub-event</span>
          <window.CertSelect value={subId} placeholder={mainEvents ? 'Choose a sub-event' : 'Loading…'} onChange={(v) => pickSub(v)} options={(mainEvents || []).flatMap((m) => [{ group: true, label: m.title }].concat(m.subEvents.map((x) => ({ value: x.id, label: x.title + ' · ' + x.date }))))} />
        </div>
        <div><span style={lbl}>Template version</span>
          <window.CertSelect value={versionN} onChange={(v) => setVersionN(+v)} options={tpl.versions.slice().reverse().map((v) => ({ value: v.n, label: 'v' + v.n + (v.n === latest ? ' (latest)' : '') }))} />
        </div>
      </div>

      {reprint && <div style={{ padding: '10px 12px', borderRadius: 10, background: 'color-mix(in srgb, var(--brand-primary) 9%, white)', border: '1px solid color-mix(in srgb, var(--brand-primary) 35%, white)', fontSize: 'var(--text-sm)', color: 'var(--navy-900)' }}><strong>Reprinting:</strong> tick the person (or people) who need a new copy below.</div>}
      <div><span style={lbl}>Who gets one</span>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(190px, 1fr))', gap: 8 }}>
          {radio('checked', 'Checked-in only', 'Paid attendees who checked in on the day')}
          {radio('paid', 'All paid', 'Everyone with a paid ticket')}
          {radio('pick', 'Hand-pick', 'Tick the attendees you want')}
        </div>
        <div style={{ marginTop: 12, display: 'flex', gap: 18, flexWrap: 'wrap' }}>
          <window.CertCheck checked={includeRefunded} onChange={setIncludeRefunded} label="Include refunded orders" />
          {scope !== 'pick' && printedCount > 0 && <window.CertCheck checked={skipPrinted} onChange={setSkipPrinted} label={'Skip ' + printedCount + ' already printed'} />}
        </div>
      </div>

      {subId && (
        <div><span style={lbl}>{atts ? chosenAtts.length + ' of ' + base.length + ' eligible attendee' + (base.length === 1 ? '' : 's') + ' selected' : 'Attendees'}</span>
          <div style={{ border: '1px solid var(--border-default)', borderRadius: 'var(--radius-md)', maxHeight: 220, overflowY: 'auto' }}>
            {!atts && <div style={{ padding: 14 }}><div className="ud-skel" style={{ height: 14, width: '60%' }}></div></div>}
            {atts && base.length === 0 && <div style={{ padding: 14, fontSize: 'var(--text-sm)', color: 'var(--text-muted)' }}>No paid attendees for this sub-event yet.</div>}
            {atts && base.map((a) => {
              const on = scope === 'pick' ? !!picked[a.ticketId] : chosenAtts.indexOf(a) !== -1;
              return (
                <div key={a.ticketId} onClick={() => { if (scope === 'pick') setPicked((p) => ({ ...p, [a.ticketId]: !on })); }} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '9px 12px', borderBottom: '1px solid var(--border-default)', fontSize: 'var(--text-sm)', cursor: scope === 'pick' ? 'pointer' : 'default', opacity: on ? 1 : 0.5 }}>
                  <span style={{ pointerEvents: 'none', display: 'inline-flex' }}><window.CertCheck disabled={scope !== 'pick'} checked={on} onChange={() => {}} /></span>
                  <span style={{ flex: 1, minWidth: 0 }}>{a.first} {a.last}<span style={{ color: 'var(--text-muted)', fontSize: 'var(--text-xs)' }}> · {a.certNumber}</span></span>
                  {printed[a.ticketId] && <span title={'By ' + printed[a.ticketId].by} style={{ fontSize: 'var(--text-xs)', color: 'var(--navy-900)', fontWeight: 600, background: 'var(--bg-sunken)', padding: '2px 8px', borderRadius: 999 }}>{printed[a.ticketId].how === 'printed' ? 'Printed' : 'Downloaded'} {pDate(printed[a.ticketId].at)}</span>}
                  {a.checkedIn && <span style={{ fontSize: 'var(--text-xs)', color: 'var(--status-success)', fontWeight: 600 }}>Checked in</span>}
                  {a.orderStatus === 'refunded' && <span style={{ fontSize: 'var(--text-xs)', color: 'var(--status-error)', fontWeight: 600 }}>Refunded</span>}
                </div>
              );
            })}
          </div>
        </div>
      )}

      {(usesHours || usesNote) && (
        <div style={{ display: 'grid', gridTemplateColumns: usesHours && usesNote ? '1fr 2fr' : '1fr', gap: 12 }}>
          {usesHours && <div><span style={lbl}>Hours / credits</span><input className="ce-input" value={hours} onChange={(e) => setHours(e.target.value)} placeholder="e.g. 8 hours" style={inp} /><div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 5 }}>Filled in from the session times. Change it if needed.</div></div>}
          {usesNote && <div><span style={lbl}>Custom note</span><input className="ce-input" value={note} onChange={(e) => setNote(e.target.value)} placeholder="e.g. With distinction" style={inp} /><div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 5 }}>Shown wherever your template has the "Custom note" detail.</div></div>}
        </div>
      )}

      <div><span style={lbl}>Order</span>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          {pill(sortBy === 'last', () => setSortBy('last'), 'Last name A–Z')}
          {pill(sortBy === 'first', () => setSortBy('first'), 'First name A–Z')}
          {pill(sortBy === 'order', () => setSortBy('order'), 'Order number')}
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(240px, 1fr))', gap: 16 }}>
        <div><span style={lbl}>Download as</span>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {[{ v: 'zip', l: 'ZIP of separate PDFs' }, { v: 'pdf', l: 'One combined PDF' }, { v: 'both', l: 'Both' }].map((o) => pill(output === o.v, () => setOutput(o.v), o.l, o.v))}
          </div>
          {chosen && <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 6 }}>ZIP files are named like {CEG.safeName(chosen.s.title)}_DelaCruz_Juan.pdf</div>}
        </div>
        <div><span style={lbl}>{CEG.DOC_TYPES[dType].label}s per sheet (combined PDF & print)</span>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
            {[1, 2, 4, 'fit'].map((n) => pill(perSheet === n, () => setPerSheet(n), n === 1 ? '1 per page' : n === 'fit' ? 'As many as fit' : n + ' per sheet', 'ps' + n))}
          </div>
          {perSheet > 1 && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 8, flexWrap: 'wrap' }}>
              <div style={{ width: 150 }}><window.CertSelect value={sheet} onChange={setSheet} options={[{ value: 'a4', label: 'A4 paper' }, { value: 'letter', label: 'Letter paper' }]} /></div>
              {L && <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>{perSheet === 'fit' ? L.per + ' per sheet at ' : 'Each prints at '}{Math.round(L.scale * 100)}% size, with cut marks.</span>}
            </div>
          )}
        </div>
      </div>
      {error && <div style={{ padding: '10px 12px', borderRadius: 'var(--radius-md)', background: 'var(--status-error-bg, #FBE7E9)', color: 'var(--status-error)', fontSize: 'var(--text-sm)' }}>{error}</div>}
    </div>
  );

  const reviewBody = (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap', padding: '12px 14px', borderRadius: 10, background: flaggedCount ? 'color-mix(in srgb, var(--status-warning, #D98E04) 10%, white)' : 'color-mix(in srgb, var(--status-success) 10%, white)', border: '1px solid ' + (flaggedCount ? 'color-mix(in srgb, var(--status-warning, #D98E04) 35%, white)' : 'color-mix(in srgb, var(--status-success) 35%, white)') }}>
        <span style={{ fontSize: 'var(--text-sm)', fontWeight: 600, flex: 1, minWidth: 200 }}>{flaggedCount ? flaggedCount + ' of ' + rows.length + ' ' + noun + ' need a quick look before printing.' : 'All ' + rows.length + ' ' + noun + ' look good.'}</span>
        {caseCount > 0 && <Button size="sm" variant="secondary" onClick={fixAllCase}>Fix capitals for all ({caseCount})</Button>}
        {flaggedCount > 0 && <window.CertCheck checked={onlyFlagged} onChange={setOnlyFlagged} label="Show only these" />}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: 14 }}>
        {shown.map((r) => (
          <div key={r.a.ticketId} style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <CertGenThumb design={design} data={r.data} flagged={r.issues.length > 0} onOpen={() => setBig(r)} />
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 4 }}>
              <input className="ce-input" value={r.a.first} onChange={(e) => editName(r.a, 'first', e.target.value)} aria-label="First name" placeholder="First name" style={{ ...inp, height: 30, padding: '0 8px', fontSize: 12, borderColor: r.a.first ? 'var(--border-default)' : 'var(--status-warning, #D98E04)' }} />
              <input className="ce-input" value={r.a.last} onChange={(e) => editName(r.a, 'last', e.target.value)} aria-label="Last name" placeholder="Last name" style={{ ...inp, height: 30, padding: '0 8px', fontSize: 12, borderColor: r.a.last ? 'var(--border-default)' : 'var(--status-warning, #D98E04)' }} />
            </div>
            {r.issues.map((i, k) => (
              <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11.5, color: '#8a5a00', lineHeight: 1.35 }}>
                <span style={{ width: 6, height: 6, borderRadius: '50%', background: 'var(--status-warning, #D98E04)', flexShrink: 0 }}></span>
                <span style={{ flex: 1 }}>{i.msg}</span>
                {i.kind === 'case' && <button type="button" onClick={() => fixCase(r.a)} style={{ border: 'none', background: 'none', color: 'var(--brand-primary)', fontWeight: 700, fontSize: 11.5, cursor: 'pointer', padding: 0, fontFamily: 'var(--font-body)' }}>Fix</button>}
              </div>
            ))}
            {fixes[r.a.ticketId] && <div style={{ display: 'flex', gap: 6, alignItems: 'center', fontSize: 11, color: 'var(--status-success)', fontWeight: 600 }}>Corrected name saved<button type="button" onClick={() => setFixes((f) => { const n = { ...f }; delete n[r.a.ticketId]; return n; })} style={{ border: 'none', background: 'none', padding: 0, color: 'var(--brand-primary)', fontWeight: 700, fontSize: 11, cursor: 'pointer', fontFamily: 'var(--font-body)' }}>Use booking name</button></div>}
            {printed[r.a.ticketId] && <div style={{ display: 'flex', gap: 6, alignItems: 'center', fontSize: 11, color: 'var(--navy-900)', fontWeight: 600 }}>{printed[r.a.ticketId].how === 'printed' ? 'Printed' : 'Downloaded'} {pDate(printed[r.a.ticketId].at)}<button type="button" onClick={() => { CEG.unmarkPrinted(r.a.ticketId); setPrinted(CEG.loadPrinted()); }} style={{ border: 'none', background: 'none', padding: 0, color: 'var(--brand-primary)', fontWeight: 700, fontSize: 11, cursor: 'pointer', fontFamily: 'var(--font-body)' }}>Mark not printed</button></div>}
            <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>{r.a.certNumber}</div>
          </div>
        ))}
      </div>
      <div style={{ fontSize: 11.5, color: 'var(--text-muted)' }}>Name corrections are remembered for next time (for reprints too), but they don't change the booking records.</div>
      {progress && (
        <div>
          <div style={{ height: 8, background: 'var(--gray-100)', borderRadius: 999, overflow: 'hidden' }}><div style={{ height: '100%', width: (progress.done / Math.max(progress.total, 1) * 100) + '%', background: 'var(--brand-primary)', transition: 'width 150ms' }}></div></div>
          <div style={{ fontSize: 'var(--text-xs)', color: 'var(--text-muted)', marginTop: 6 }}>{progress.done} of {progress.total} pages ready</div>
        </div>
      )}
      {error && <div style={{ padding: '10px 12px', borderRadius: 'var(--radius-md)', background: 'var(--status-error-bg, #FBE7E9)', color: 'var(--status-error)', fontSize: 'var(--text-sm)' }}>{error}</div>}
    </div>
  );

  const dlLabel = output === 'zip' ? 'Download ZIP' : output === 'pdf' ? 'Download PDF' : 'Download ZIP + PDF';
  return (
    <>
      <CertModal open onClose={running || big ? () => {} : onClose} width={step === 'review' ? 980 : 760} title={(step === 'review' ? 'Review ' + rows.length + ' ' + noun : 'Generate ' + noun) + ' · ' + tpl.name}
        footer={step === 'setup' ? <>
          <Button variant="secondary" onClick={onClose}>Cancel</Button>
          <Button onClick={() => { setStep('review'); setOnlyFlagged(false); }} disabled={!chosen || !chosenAtts.length}>Review {chosenAtts.length || ''} {chosenAtts.length === 1 ? nounOne : noun} →</Button>
        </> : <>
          <Button variant="secondary" onClick={() => setStep('setup')} disabled={running}>← Back</Button>
          <span style={{ flex: 1 }}></span>
          <Button variant="secondary" onClick={() => run('print')} disabled={running || !rows.length}>{running ? 'Preparing…' : 'Print all'}</Button>
          <Button onClick={() => run('download')} disabled={running || !rows.length}>{running ? 'Preparing…' : dlLabel}</Button>
        </>}>
        {step === 'setup' ? setupBody : reviewBody}
      </CertModal>
      <CertModal open={!!big} onClose={() => setBig(null)} width={960} title={big ? (big.a.first + ' ' + big.a.last).trim() || 'Certificate' : ''}>
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          {bigSrc ? <img src={bigSrc} alt="" style={{ maxWidth: '100%', maxHeight: '70vh', boxShadow: 'var(--shadow-md)', borderRadius: 4 }} /> : <div className="ud-skel" style={{ width: '100%', aspectRatio: design.page.w + ' / ' + design.page.h, maxHeight: '70vh' }}></div>}
        </div>
      </CertModal>
    </>
  );
}

window.CertGenerateDialog = CertGenerateDialog;
