const CEL = window.CertEngine;

function certFmt(iso) { if (!iso) return '—'; return new Date(iso).toLocaleString('en-US', { month: 'short', day: 'numeric', year: 'numeric', hour: 'numeric', minute: '2-digit' }); }
function certPageLabel(page) { if (page.size === 'custom') return Math.round(page.w / CEL.MM) + ' × ' + Math.round(page.h / CEL.MM) + ' mm'; return (CEL.PAGE_BASE[page.size] || {}).label + ' ' + page.orientation; }

function CertThumb({ design, width, style, frame }) {
  const [src, setSrc] = React.useState(null);
  const key = JSON.stringify(design);
  React.useEffect(() => { let live = true; setSrc(null); CEL.thumbnail(design, Math.round(width * 1.6)).then((u) => { if (live) setSrc(u); }).catch(() => {}); return () => { live = false; }; }, [key, width]);
  const ratio = design.page.h / design.page.w;
  if (frame) {
    const boxRatio = typeof frame === 'number' ? frame : 0.68;
    const portrait = ratio > boxRatio;
    return (
      <div style={{ width: '100%', aspectRatio: '1 / ' + boxRatio, background: 'var(--bg-sunken)', borderRadius: 8, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '7%', boxSizing: 'border-box', overflow: 'hidden', ...style }}>
        {src
          ? <img src={src} alt="" style={{ display: 'block', width: portrait ? 'auto' : '100%', height: portrait ? '100%' : 'auto', maxWidth: '100%', maxHeight: '100%', aspectRatio: '1 / ' + ratio, boxShadow: '0 3px 14px rgba(14,34,71,0.16)', borderRadius: 3 }} />
          : <div className="ud-skel" style={{ width: portrait ? 'auto' : '100%', height: portrait ? '100%' : 'auto', aspectRatio: '1 / ' + ratio, borderRadius: 3 }}></div>}
      </div>
    );
  }
  return src
    ? <img src={src} alt="" style={{ width: '100%', aspectRatio: '1 / ' + ratio, display: 'block', objectFit: 'cover', borderRadius: 6, boxShadow: '0 2px 10px rgba(14,34,71,0.12)', ...style }} />
    : <div className="ud-skel" style={{ width: '100%', aspectRatio: '1 / ' + ratio, borderRadius: 6, ...style }}></div>;
}

function CertModal({ open, onClose, width, title, children, footer }) {
  const ctxLeaving = React.useContext(window.CertLeaveCtx);
  const [shown, setShown] = React.useState(open);
  const [out, setOut] = React.useState(false);
  const kept = React.useRef({ title, children, footer });
  if (open) kept.current = { title, children, footer };
  React.useEffect(() => {
    if (open) { setShown(true); setOut(false); return; }
    if (!shown) return;
    setOut(true);
    const t = setTimeout(() => { setShown(false); setOut(false); }, 200);
    return () => clearTimeout(t);
  }, [open]);
  React.useEffect(() => {
    if (!open) return;
    const k = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', k); return () => window.removeEventListener('keydown', k);
  }, [open, onClose]);
  if (!open && !shown) return null;
  const leaving = ctxLeaving || out || !open;
  const v = open ? { title, children, footer } : kept.current;
  title = v.title; children = v.children; footer = v.footer;
  return ReactDOM.createPortal(
    <div onClick={leaving ? undefined : onClose} className={'ce-modal-bd' + (leaving ? ' ce-out' : '')} style={{ position: 'fixed', inset: 0, background: 'rgba(8,21,27,0.6)', zIndex: 1250, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }}>
      <div onClick={(e) => e.stopPropagation()} className="ce-modal-panel" style={{ width: 'min(' + (width || 640) + 'px, 100%)', maxHeight: '92vh', display: 'flex', flexDirection: 'column', background: 'white', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-lg)', overflow: 'hidden' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '18px 22px', borderBottom: '1px solid var(--border-default)' }}>
          <div style={{ flex: 1, minWidth: 0, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'var(--text-lg)' }}>{title}</div>
          <button type="button" onClick={onClose} aria-label="Close" style={{ width: 32, height: 32, borderRadius: '50%', border: 'none', background: 'var(--bg-sunken)', cursor: 'pointer', fontSize: 18, flexShrink: 0 }}>×</button>
        </div>
        <div style={{ flex: 1, minHeight: 0, overflowY: 'auto', padding: 22 }}>{children}</div>
        {footer && <div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end', flexWrap: 'wrap', padding: '14px 22px', borderTop: '1px solid var(--border-default)', background: 'var(--bg-sunken)' }}>{footer}</div>}
      </div>
    </div>,
    document.body
  );
}

function CertStarterPicker({ open, onClose, onPick }) {
  const starters = React.useMemo(() => CEL.starters(), [open]);
  const printables = React.useMemo(() => CEL.printableStarters(), [open]);
  const card = (s) => (
    <button key={s.key} type="button" onClick={() => onPick(s)} className="ce-btn ce-tile" style={{ border: '1px solid var(--border-default)', borderRadius: 'var(--radius-md)', padding: 10, background: 'white', cursor: 'pointer', textAlign: 'left', display: 'flex', flexDirection: 'column', gap: 10, fontFamily: 'var(--font-body)' }}>
      <div style={{ height: 130, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--bg-sunken)', borderRadius: 6, overflow: 'hidden' }}><CertThumb design={s.design} width={s.design.page.w >= s.design.page.h ? 180 : Math.round(120 * s.design.page.w / s.design.page.h)} /></div>
      <div style={{ fontWeight: 700, fontSize: 'var(--text-sm)', color: 'var(--text-primary)' }}>{s.name}</div>
    </button>
  );
  const h3 = { fontSize: 'var(--text-xs)', fontWeight: 700, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.06em', margin: '0 0 10px' };
  return (
    <CertModal open={open} onClose={onClose} width={900} title="Start a new template">
      <div style={h3}>Certificates</div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(190px, 1fr))', gap: 16, marginBottom: 22 }}>{starters.map(card)}</div>
      <div style={h3}>Name badges, table cards & signs</div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(190px, 1fr))', gap: 16 }}>{printables.map(card)}</div>
      <div style={{ display: 'none' }}>
        {[].map((s) => (
          <button key={s.key} type="button" onClick={() => onPick(s)} style={{ border: '1px solid var(--border-default)', borderRadius: 'var(--radius-md)', padding: 10, background: 'white', cursor: 'pointer', textAlign: 'left', display: 'flex', flexDirection: 'column', gap: 10, fontFamily: 'var(--font-body)' }}>
            <CertThumb design={s.design} width={190} />
            <div style={{ fontWeight: 700, fontSize: 'var(--text-sm)', color: 'var(--text-primary)' }}>{s.name}</div>
          </button>
        ))}
      </div>
      <div style={{ fontSize: 'var(--text-xs)', color: 'var(--text-muted)', marginTop: 14 }}>Every starter is fully editable. You can change the page size, colours, and every element in the editor.</div>
    </CertModal>
  );
}

function CertTagFilter({ tags, value, onChange }) {
  const [open, setOpen] = React.useState(false);
  const [q, setQ] = React.useState('');
  const [shown, leaving] = window.useUdPresence(open, 140);
  const ref = React.useRef(null);
  React.useEffect(() => { if (!open) return; const f = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); }; const k = (e) => { if (e.key === 'Escape') setOpen(false); }; document.addEventListener('mousedown', f); window.addEventListener('keydown', k); return () => { document.removeEventListener('mousedown', f); window.removeEventListener('keydown', k); }; }, [open]);
  React.useEffect(() => { if (!open) setQ(''); }, [open]);
  const list = tags.filter((t) => !q || t.indexOf(q.toLowerCase().replace(/^#/, '')) !== -1);
  const on = !!value;
  return (
    <div ref={ref} style={{ position: 'relative' }}>
      <button type="button" className="ce-pill" onClick={() => setOpen((o) => !o)} style={{ height: 32, padding: '0 12px', borderRadius: 999, border: '1.5px solid ' + (on || open ? 'var(--navy-900)' : 'var(--border-default)'), background: on ? 'var(--navy-900)' : 'white', color: on ? 'white' : 'var(--navy-900)', fontSize: 12.5, fontWeight: 600, cursor: 'pointer', fontFamily: 'var(--font-body)', whiteSpace: 'nowrap', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
        {on ? '#' + value : 'Tags (' + tags.length + ')'}
        <svg width="11" height="11" viewBox="0 0 12 12" style={{ transform: open ? 'rotate(180deg)' : 'none', transition: 'transform .18s ease' }}><path d="M2.5 4.5L6 8l3.5-3.5" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" /></svg>
      </button>
      {shown && (
        <div className={'ce-pop' + (leaving ? ' ce-out' : '')} style={{ position: 'absolute', left: 0, top: 'calc(100% + 6px)', zIndex: 40, width: 240, background: 'white', border: '1px solid var(--border-default)', borderRadius: 12, boxShadow: '0 14px 32px rgba(5,13,26,.18)', padding: 8 }}>
          <input autoFocus value={q} onChange={(e) => setQ(e.target.value)} placeholder="Search tags" style={{ width: '100%', height: 34, boxSizing: 'border-box', padding: '0 10px', borderRadius: 8, border: '1.5px solid var(--border-default)', fontSize: 13, fontFamily: 'var(--font-body)', outline: 'none', marginBottom: 6 }} />
          <div style={{ maxHeight: 220, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 2 }} onWheel={(e) => e.stopPropagation()}>
            {on && <button type="button" className="cg-navbtn" onClick={() => { onChange(''); setOpen(false); }} style={{ textAlign: 'left', border: 'none', background: 'white', padding: '8px 10px', borderRadius: 8, fontSize: 13, color: 'var(--brand-primary)', fontWeight: 700, cursor: 'pointer', fontFamily: 'var(--font-body)' }}>Show all tags</button>}
            {list.map((t) => (
              <button key={t} type="button" className="cg-navbtn" onClick={() => { onChange(t === value ? '' : t); setOpen(false); }} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', textAlign: 'left', border: 'none', background: t === value ? 'color-mix(in srgb, var(--brand-primary) 12%, white)' : 'white', padding: '8px 10px', borderRadius: 8, fontSize: 13, color: 'var(--navy-900)', fontWeight: t === value ? 700 : 500, cursor: 'pointer', fontFamily: 'var(--font-body)' }}>#{t}{t === value && <span style={{ color: 'var(--brand-primary)' }}>✓</span>}</button>
            ))}
            {list.length === 0 && <div style={{ padding: '8px 10px', fontSize: 12.5, color: 'var(--text-muted)' }}>No tags match.</div>}
          </div>
        </div>
      )}
    </div>
  );
}

function CertMetaRow({ tpl, onChanged, adminName }) {
  const curD = CEL.current(tpl), dt = CEL.docType(curD);
  function setType(v) { if (v === dt) return; CEL.saveVersion(tpl.id, { ...curD, settings: { ...(curD.settings || {}), docType: v } }, adminName, 'Marked as ' + CEL.DOC_TYPES[v].label.toLowerCase()); onChanged(); }
  const [draft, setDraft] = React.useState('');
  const tags = tpl.tags || [];
  const [focus, setFocus] = React.useState(false);
  const known = Array.from(new Set(CEL.loadTemplates().flatMap((x) => x.tags || []))).filter((tg) => tags.indexOf(tg) === -1).sort();
  const q = draft.trim().replace(/^#/, '').toLowerCase();
  const sugg = known.filter((tg) => !q || tg.indexOf(q) !== -1).slice(0, 8);
  function addTag(v) { if (!v || tags.indexOf(v) !== -1) { setDraft(''); return; } CEL.setTemplateMeta(tpl.id, { tags: tags.concat([v]) }); setDraft(''); onChanged(); }
  function add() { const v = draft.trim().replace(/^#/, '').toLowerCase().replace(/\s+/g, '-'); if (!v || tags.indexOf(v) !== -1) { setDraft(''); return; } CEL.setTemplateMeta(tpl.id, { tags: tags.concat([v]) }); setDraft(''); onChanged(); }
  function remove(tg) { CEL.setTemplateMeta(tpl.id, { tags: tags.filter((x) => x !== tg) }); onChanged(); }
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginBottom: 16 }}>
      <div style={{ width: 170 }} title="What this design is for. Used by the filters on the templates page."><window.CertSelect value={dt} onChange={setType} options={Object.keys(CEL.DOC_TYPES).map((k) => ({ value: k, label: CEL.DOC_TYPES[k].label }))} /></div>
      <button type="button" onClick={() => { CEL.setTemplateMeta(tpl.id, { favorite: !tpl.favorite }); onChanged(); }} style={{ height: 30, padding: '0 12px', borderRadius: 999, border: '1.5px solid ' + (tpl.favorite ? '#E8A317' : 'var(--border-default)'), background: tpl.favorite ? '#FFF6DE' : 'white', color: tpl.favorite ? '#8a5a00' : 'var(--navy-900)', fontWeight: 600, fontSize: 12.5, cursor: 'pointer', fontFamily: 'var(--font-body)' }}>{tpl.favorite ? '★ Favourite' : '☆ Add to favourites'}</button>
      {tags.map((tg) => <span key={tg} style={{ display: 'inline-flex', alignItems: 'center', gap: 4, height: 28, padding: '0 6px 0 10px', borderRadius: 999, background: 'color-mix(in srgb, var(--brand-primary) 12%, white)', fontSize: 12.5, fontWeight: 600, color: 'var(--navy-900)' }}>#{tg}<button type="button" aria-label={'Remove tag ' + tg} onClick={() => remove(tg)} style={{ border: 'none', background: 'none', cursor: 'pointer', color: 'var(--text-muted)', fontSize: 14, padding: '0 2px' }}>×</button></span>)}
      <div style={{ position: 'relative' }}>
        <input className="ce-input" value={draft} onChange={(e) => setDraft(e.target.value)} onFocus={() => setFocus(true)} onBlur={() => setTimeout(() => setFocus(false), 150)} onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); add(); } if (e.key === 'Escape') { setDraft(''); e.currentTarget.blur(); } }} placeholder="+ Add tag, press Enter" style={{ height: 30, width: 170, padding: '0 10px', borderRadius: 999, border: '1.5px dashed var(--border-default)', fontSize: 12.5, fontFamily: 'var(--font-body)', outline: 'none' }} />
        {focus && (sugg.length > 0 || q) && (
          <div className="ce-pop" style={{ position: 'absolute', left: 0, top: 'calc(100% + 6px)', zIndex: 30, width: 230, background: 'white', border: '1px solid var(--border-default)', borderRadius: 12, boxShadow: '0 14px 32px rgba(5,13,26,.18)', padding: 8, display: 'flex', flexDirection: 'column', gap: 6 }}>
            {sugg.length > 0 && <div style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: '.06em', textTransform: 'uppercase', color: 'var(--text-muted)', padding: '2px 4px' }}>Tags already in use</div>}
            {sugg.length > 0 && <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5 }}>{sugg.map((tg) => <button key={tg} type="button" className="ce-pill" onMouseDown={(e) => { e.preventDefault(); addTag(tg); }} style={{ height: 26, padding: '0 10px', borderRadius: 999, border: '1.5px solid var(--border-default)', background: 'white', color: 'var(--navy-900)', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'var(--font-body)' }}>#{tg}</button>)}</div>}
            {q && known.indexOf(q.replace(/\s+/g, '-')) === -1 && tags.indexOf(q.replace(/\s+/g, '-')) === -1 && <div style={{ fontSize: 12, color: 'var(--text-secondary)', padding: '2px 4px' }}>Press <b>Enter</b> to create <b>#{q.replace(/\s+/g, '-')}</b></div>}
          </div>
        )}
      </div>
    </div>
  );
}

const certSecHead = { display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12, fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'var(--text-base)', color: 'var(--navy-900)' };
const certSecCount = { fontFamily: 'var(--font-body)', fontSize: 11.5, fontWeight: 700, color: 'var(--text-muted)', background: 'var(--bg-sunken)', padding: '2px 8px', borderRadius: 999 };
const certVerAct = { height: 32, padding: '0 11px', border: 'none', background: 'white', color: 'var(--navy-900)', fontWeight: 600, fontSize: 12.5, cursor: 'pointer', fontFamily: 'var(--font-body)', display: 'inline-flex', alignItems: 'center', gap: 6, whiteSpace: 'nowrap' };

function CertDetails({ tpl, isMobile, adminName, onClose, onEdit, onGenerate, onReprint, onChanged }) {
  const { Button } = window.TheUpperDeckDesignSystem_4d3294;
  const [tab, setTab] = React.useState('versions');
  const [viewing, setViewing] = React.useState(null);
  const [comparing, setComparing] = React.useState(null);
  const [busy, setBusy] = React.useState(false);
  const cur = CEL.current(tpl), latest = tpl.versions[tpl.versions.length - 1];
  const meta = (label, value, sub) => (
    <div style={{ background: 'var(--bg-sunken)', borderRadius: 'var(--radius-md)', padding: '10px 12px', minWidth: 0 }}>
      <div style={{ fontSize: 'var(--text-xs)', color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>{label}</div>
      <div style={{ fontWeight: 600, fontSize: 'var(--text-sm)', marginTop: 3 }}>{value}</div>
      {sub && <div style={{ fontSize: 'var(--text-xs)', color: 'var(--text-secondary)', marginTop: 1 }}>{sub}</div>}
    </div>
  );
  async function exportSample() { setBusy(true); try { CEL.download(await CEL.buildCombinedPdf(cur, [null]), CEL.safeName(tpl.name) + '.pdf'); } finally { setBusy(false); } }
  async function restore(n) { if (!(await window.udConfirm('Restore version ' + n + '? It will be saved as a new version, so nothing is lost.'))) return; CEL.restoreVersion(tpl.id, n, adminName); setViewing(null); onChanged(); }
  async function remove() { if (!(await window.udConfirm('Delete "' + tpl.name + '" and all its versions?'))) return; CEL.deleteTemplate(tpl.id); onChanged(); onClose(); }
  function duplicate() { CEL.duplicateTemplate(tpl.id, adminName); onChanged(); onClose(); }
  const tabBtn = (v, l) => <button type="button" className="ud-tabbtn" onClick={() => setTab(v)} style={{ padding: '10px 4px', marginRight: 18, border: 'none', borderBottom: tab === v ? '2px solid var(--brand-primary)' : '2px solid transparent', background: 'none', fontWeight: tab === v ? 700 : 500, cursor: 'pointer', fontSize: 'var(--text-sm)', color: 'var(--text-primary)', fontFamily: 'var(--font-body)' }}>{l}</button>;
  const fmtLabel = { zip: 'ZIP', pdf: 'Combined PDF', both: 'ZIP + PDF', print: 'Printed' };

  return (
    <>
      <CertModal open onClose={onClose} width={900} title={tpl.name}
        footer={<>
          <button type="button" onClick={remove} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, height: 36, padding: '0 12px', border: 'none', background: 'none', color: 'var(--status-error)', fontWeight: 600, fontSize: 13.5, cursor: 'pointer', fontFamily: 'var(--font-body)', borderRadius: 8 }} className="ce-btn"><svg width="15" height="15" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"><path d="M3 4.5h10M6.5 4.5V3h3v1.5M4.5 4.5l.6 8.5h5.8l.6-8.5" /></svg>Delete template</button>
          <span style={{ flex: 1 }}></span>
          <Button variant="secondary" onClick={onClose}>Close</Button>
        </>}>
        <CertMetaRow tpl={tpl} onChanged={onChanged} adminName={adminName} />
        <div className="ud-cert-detail" style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1.25fr) minmax(0,1fr)', gap: 22 }}>
          <CertThumb design={cur} width={480} frame={0.72} />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12, minWidth: 0 }}>
            <div style={{ fontSize: 'var(--text-sm)', color: tpl.description ? 'var(--text-secondary)' : 'var(--text-muted)', lineHeight: 1.5 }}>{tpl.description || 'No description.'}</div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
              {meta('Created', certFmt(tpl.createdAt), tpl.createdBy)}
              {meta('Last updated', certFmt(tpl.updatedAt), tpl.updatedBy)}
              {meta('Current version', 'v' + latest.n, latest.note)}
              {meta('Page', certPageLabel(cur.page), cur.background.type === 'pdf' ? 'Uses an uploaded PDF' : null)}
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 'auto', paddingTop: 4 }}>
              <button type="button" onClick={() => onGenerate(tpl, null)} className="ce-btn ce-btn-primary" style={{ height: 46, border: 'none', borderRadius: 10, background: 'var(--brand-primary)', color: 'white', fontWeight: 700, fontSize: 15, cursor: 'pointer', fontFamily: 'var(--font-body)', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}><svg width="17" height="17" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round"><path d="M4 6V2h8v4M4 12H2.5V7.5a1.5 1.5 0 011.5-1.5h8a1.5 1.5 0 011.5 1.5V12H12M4.5 10h7v4h-7z" /></svg><span>Generate {CEL.DOC_TYPES[CEL.docType(cur)].plural}</span></button>
              {!isMobile && <button type="button" onClick={() => onEdit(tpl)} className="ce-btn ce-btn-outline" style={{ height: 42, border: '1.5px solid var(--navy-900)', borderRadius: 10, background: 'white', color: 'var(--navy-900)', fontWeight: 700, fontSize: 14, cursor: 'pointer', fontFamily: 'var(--font-body)', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}><svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"><path d="M11 2.5l2.5 2.5L6 12.5 3 13l.5-3z" /></svg>Edit design</button>}
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, minmax(0,1fr))', gap: 6 }}>
                {[
                  ['Duplicate', duplicate, 'M5.5 5.5h7v7h-7zM3.5 10.5v-7h7'],
                  [busy ? 'Working…' : 'Export PDF', exportSample, 'M8 2.5v7M5 6.5l3 3 3-3M3 12.5h10'],
                  ['Test print', async () => { setBusy(true); try { CEL.printBlob(await CEL.buildTestPdf(cur, null)); } finally { setBusy(false); } }, 'M4.5 6V2.5h7V6M4.5 11H3V7.5h10V11h-1.5M5 9.5h6v4H5z'],
                ].map(([l, fn, d]) => (
                  <button key={l} type="button" onClick={fn} disabled={busy} className="ce-btn ce-tile" style={{ height: 58, border: '1px solid var(--border-default)', borderRadius: 10, background: 'white', color: 'var(--navy-900)', fontWeight: 600, fontSize: 12.5, cursor: 'pointer', fontFamily: 'var(--font-body)', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 5, padding: '0 4px' }}>
                    <svg width="18" height="18" viewBox="0 0 16 16" fill="none" stroke="var(--brand-primary)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"><path d={d} /></svg>
                    <span style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '100%' }}>{l}</span>
                  </button>
                ))}
              </div>
            </div>
          </div>
        </div>
        <div style={{ borderBottom: '1px solid var(--border-default)', marginTop: 22 }}>{tabBtn('versions', 'Versions (' + tpl.versions.length + ')')}{tabBtn('history', 'Generation history (' + tpl.history.length + ')')}</div>
        <div key={tab} className="ud-tab-panel">{tab === 'versions' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, paddingTop: 12 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div style={{ flex: 1, fontSize: 'var(--text-sm)', color: 'var(--text-muted)' }}>Every save is kept. Open any version to look at it, bring it back, or print from it.</div>
              {tpl.versions.length > 1 && <button type="button" className="ce-btn ce-btn-outline" onClick={() => setComparing({ a: tpl.versions[tpl.versions.length - 2].n, b: latest.n })} style={{ ...certVerAct, border: '1.5px solid var(--navy-900)', borderRadius: 8, height: 34, padding: '0 14px', flexShrink: 0 }}><svg width="15" height="15" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"><path d="M2.5 3.5h4.5v9H2.5zM9 3.5h4.5v9H9z" /></svg>Compare versions</button>}
            </div>
            {tpl.versions.slice().reverse().map((v) => {
              const isCur = v.n === latest.n;
              return (
                <div key={v.n} className="ud-ver-row" style={{ display: 'grid', gridTemplateColumns: '52px minmax(0,1fr) auto', gap: 14, alignItems: 'center', padding: '12px 14px', border: '1px solid ' + (isCur ? 'color-mix(in srgb, var(--brand-primary) 45%, white)' : 'var(--border-default)'), background: isCur ? 'color-mix(in srgb, var(--brand-primary) 5%, white)' : 'white', borderRadius: 10 }}>
                  <span style={{ display: 'inline-flex', alignItems: 'center', justifyContent: 'center', height: 30, borderRadius: 8, background: isCur ? 'var(--brand-primary)' : 'var(--navy-900)', color: 'white', fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: 13 }}>v{v.n}</span>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
                      <span style={{ fontSize: 'var(--text-sm)', fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{v.note || 'Saved'}</span>
                      {isCur && <span style={{ flexShrink: 0, fontSize: 11, fontWeight: 700, padding: '2px 8px', borderRadius: 999, background: 'color-mix(in srgb, var(--status-success) 14%, white)', color: 'var(--status-success)' }}>Current</span>}
                    </div>
                    <div style={{ fontSize: 'var(--text-xs)', color: 'var(--text-muted)', marginTop: 2 }}>{certFmt(v.savedAt)} · {v.savedBy || '—'}</div>
                  </div>
                  <div className="ud-ver-acts" style={{ display: 'inline-flex', border: '1px solid var(--border-default)', borderRadius: 8, overflow: 'hidden', background: 'white' }}>
                    <button type="button" className="ce-btn ce-seg" onClick={() => setViewing(v)} style={certVerAct} title="Look at this version"><svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6"><path d="M1.5 8S4 3.5 8 3.5 14.5 8 14.5 8 12 12.5 8 12.5 1.5 8 1.5 8z" /><circle cx="8" cy="8" r="2" /></svg>View</button>
                    {!isCur && <button type="button" className="ce-btn ce-seg" onClick={() => restore(v.n)} style={{ ...certVerAct, borderLeft: '1px solid var(--border-default)' }} title="Make this the current version again"><svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"><path d="M3 8a5 5 0 105-5H5M5 1v2.5H7.5" /></svg>Restore</button>}
                    <button type="button" className="ce-btn ce-seg" onClick={() => onGenerate(tpl, v.n)} style={{ ...certVerAct, borderLeft: '1px solid var(--border-default)', color: 'var(--brand-primary)' }} title="Generate from this version"><svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round"><path d="M4.5 6V2.5h7V6M4.5 11H3V7.5h10V11h-1.5M5 9.5h6v4H5z" /></svg>Generate</button>
                  </div>
                </div>
              );
            })}
          </div>
        )}
        {tab === 'history' && (
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            {tpl.history.length === 0 && <div style={{ padding: '16px 0', fontSize: 'var(--text-sm)', color: 'var(--text-muted)' }}>Nothing generated from this template yet.</div>}
            {tpl.history.map((h, i) => (
              <div key={i} style={{ display: 'flex', gap: 12, padding: '12px 0', borderBottom: '1px solid var(--border-default)', alignItems: 'center', flexWrap: 'wrap' }}>
                <div style={{ flex: 1, minWidth: 180 }}>
                  <div style={{ fontSize: 'var(--text-sm)', fontWeight: 600 }}>{h.subEventTitle}</div>
                  <div style={{ fontSize: 'var(--text-xs)', color: 'var(--text-muted)' }}>{certFmt(h.at)} · {h.by}</div>
                </div>
                <span style={{ fontSize: 'var(--text-sm)' }}>{h.count} {h.count === 1 ? CEL.DOC_TYPES[CEL.docType(cur)].label.toLowerCase() : CEL.DOC_TYPES[CEL.docType(cur)].plural}</span>
                <span style={{ fontSize: 'var(--text-xs)', color: 'var(--text-secondary)', background: 'var(--bg-sunken)', padding: '3px 8px', borderRadius: 999 }}>{fmtLabel[h.format] || h.format} · v{h.version}</span>
                <window.UdUI.Btn size="sm" variant="secondary" disabled={!h.subEventId} onClick={() => onReprint(tpl, h)}>Reprint one</window.UdUI.Btn>
              </div>
            ))}
          </div>
        )}</div>
      </CertModal>
      <CertModal open={!!comparing} onClose={() => setComparing(null)} width={1000} title={'Compare versions · ' + tpl.name}>
        {comparing && (() => {
          const va = CEL.versionDesign(tpl, comparing.a), vb = CEL.versionDesign(tpl, comparing.b), diff = CEL.diffVersions(va, vb);
          const opts = tpl.versions.slice().reverse().map((v) => ({ value: v.n, label: 'v' + v.n + ' · ' + (v.note || '') }));
          const col = (k, d) => (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, minWidth: 0 }}>
              <window.CertSelect value={comparing[k]} onChange={(v) => setComparing((cmp) => ({ ...cmp, [k]: +v }))} options={opts} />
              <div style={{ border: '1px solid var(--border-default)', borderRadius: 8, padding: 8, background: 'var(--bg-sunken)' }}><CertThumb design={d} width={440} /></div>
            </div>
          );
          const color = { add: 'var(--status-success)', remove: 'var(--status-error)', change: 'var(--navy-900)', page: '#8a5a00', bg: '#8a5a00', order: 'var(--text-muted)' };
          return (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>{col('a', va)}{col('b', vb)}</div>
              <div>
                <div style={{ fontSize: 'var(--text-xs)', fontWeight: 700, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 8 }}>What changed from v{comparing.a} to v{comparing.b}</div>
                {diff.length === 0 ? <div style={{ fontSize: 'var(--text-sm)', color: 'var(--text-muted)' }}>No differences.</div> : (
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 4, maxHeight: 220, overflowY: 'auto' }}>
                    {diff.map((d, i) => <div key={i} style={{ display: 'flex', gap: 8, alignItems: 'baseline', fontSize: 'var(--text-sm)' }}><span style={{ width: 8, height: 8, borderRadius: '50%', background: color[d.kind], flexShrink: 0, transform: 'translateY(-1px)' }}></span><span>{d.text}</span></div>)}
                  </div>
                )}
              </div>
            </div>
          );
        })()}
      </CertModal>
      {viewing && (
        <CertModal open onClose={() => setViewing(null)} width={820} title={tpl.name + ' · v' + viewing.n}
          footer={<>
            {viewing.n !== latest.n && <Button variant="secondary" onClick={() => restore(viewing.n)}>Restore this version</Button>}
            <Button onClick={() => { const n = viewing.n; setViewing(null); onGenerate(tpl, n); }}>Generate from this version</Button>
          </>}>
          <CertThumb design={viewing.snapshot} width={760} />
          <div style={{ fontSize: 'var(--text-xs)', color: 'var(--text-muted)', marginTop: 10 }}>{viewing.note} · {certFmt(viewing.savedAt)} · {viewing.savedBy}</div>
        </CertModal>
      )}
    </>
  );
}

function CertCreatorScreen({ adminUser }) {
  const { Button } = window.TheUpperDeckDesignSystem_4d3294;
  const adminName = adminUser ? ((adminUser.first_name || '') + ' ' + (adminUser.last_name || '')).trim() || adminUser.email : 'Admin';
  const [templates, setTemplates] = React.useState(() => CEL.loadTemplates());
  const [isMobile, setIsMobile] = React.useState(() => window.matchMedia('(max-width: 899px)').matches);
  const [starterOpen, setStarterOpen] = React.useState(false);
  const [editor, setEditor] = React.useState(null);
  const [detailsId, setDetailsId] = React.useState(null);
  const [gen, setGen] = React.useState(null);
  const [search, setSearch] = React.useState('');
  const [typeFilter, setTypeFilter] = React.useState('all');
  const [tagFilter, setTagFilter] = React.useState('');
  const [favOnly, setFavOnly] = React.useState(false);
  const [createdBy, setCreatedBy] = React.useState('');
  const [vw, setVw] = React.useState(window.innerWidth);
  React.useEffect(() => { const f = () => setVw(window.innerWidth); window.addEventListener('resize', f); return () => window.removeEventListener('resize', f); }, []);
  const tagLimit = 2;
  const [updatedBy, setUpdatedBy] = React.useState('');
  const [busy, setBusy] = React.useState('');
  const [error, setError] = React.useState('');
  const pdfInput = React.useRef(null);

  React.useEffect(() => { const mq = window.matchMedia('(max-width: 899px)'), f = () => setIsMobile(mq.matches); mq.addEventListener('change', f); return () => mq.removeEventListener('change', f); }, []);
  function refresh() { setTemplates(CEL.loadTemplates()); }

  function openNew(design, name) { setStarterOpen(false); setEditor({ tplId: null, design, name: name || '', description: '' }); }
  async function openEdit(tpl) {
    setDetailsId(null);
    const dr = CEL.loadDraft(tpl.id);
    if (dr && dr.at > tpl.updatedAt) {
      if ((await window.udConfirm({ title: 'Restore unsaved changes?', message: 'You have unsaved changes to "' + tpl.name + '" from ' + certFmt(dr.at) + '.', okLabel: 'Restore changes', cancelLabel: 'Open saved version', danger: false }))) { setEditor({ tplId: tpl.id, design: dr.design, name: dr.name, description: dr.description, restored: true }); return; }
      CEL.clearDraft(tpl.id);
    }
    setEditor({ tplId: tpl.id, design: CEL.current(tpl), name: tpl.name, description: tpl.description });
  }
  async function startNew() {
    const dr = CEL.loadDraft('new');
    if (dr) {
      if ((await window.udConfirm({ title: 'Restore your unsaved template?', message: 'You have an unsaved new template' + (dr.name ? ' ("' + dr.name + '")' : '') + ' from ' + certFmt(dr.at) + '.', okLabel: 'Restore it', cancelLabel: 'Start fresh', danger: false }))) { setEditor({ tplId: null, design: dr.design, name: dr.name, description: dr.description, restored: true }); return; }
      CEL.clearDraft('new');
    }
    setStarterOpen(true);
  }
  async function onPdf(file) {
    if (!file) return; setError(''); setBusy('Reading PDF…');
    try {
      const r = await CEL.pdfToBackground(file), id = CEL.putAsset(r.dataUrl);
      openNew({ page: { size: 'custom', orientation: r.w > r.h ? 'landscape' : 'portrait', w: r.w, h: r.h }, background: { type: 'pdf', image: id, fileName: file.name }, elements: [] }, file.name.replace(/\.pdf$/i, ''));
    } catch (e) { setError(e.message || 'Could not read that PDF.'); }
    setBusy('');
  }
  async function onSave(meta, design) {
    if (!editor.tplId) {
      const t = CEL.createTemplate(meta.name, meta.description, design, adminName);
      setEditor((ed) => ({ ...ed, tplId: t.id })); refresh(); return 1;
    }
    const t = CEL.saveVersion(editor.tplId, design, adminName, (meta.note || '').trim() || 'Edited', { name: meta.name, description: meta.description }); refresh(); return t.versions[t.versions.length - 1].n;
  }

  const editingTpl = editor && editor.tplId ? templates.find((t) => t.id === editor.tplId) : null;
  const detailsTpl = detailsId ? templates.find((t) => t.id === detailsId) : null;
  const allTags = Array.from(new Set(templates.flatMap((t) => t.tags || []))).sort();
  const people = (k) => Array.from(new Set(templates.map((t) => t[k]).filter(Boolean))).sort();
  const anyFilter = typeFilter !== 'all' || favOnly || tagFilter || createdBy || updatedBy || search;
  const shown = templates.filter((t) => {
    const ty = CEL.docType(CEL.current(t));
    if (typeFilter !== 'all' && ty !== typeFilter) return false;
    if (favOnly && !t.favorite) return false;
    if (tagFilter && (t.tags || []).indexOf(tagFilter) === -1) return false;
    if (createdBy && (t.createdBy || '') !== createdBy) return false;
    if (updatedBy && (t.updatedBy || '') !== updatedBy) return false;
    return !search || (t.name + ' ' + t.description + ' ' + (t.tags || []).join(' ')).toLowerCase().indexOf(search.toLowerCase()) !== -1;
  }).sort((a, b) => (b.favorite ? 1 : 0) - (a.favorite ? 1 : 0));
  const fpill = (on, onClick, label, k) => <button key={k || label} type="button" className="ce-pill" onClick={onClick} style={{ height: 32, padding: '0 12px', borderRadius: 999, border: '1.5px solid ' + (on ? 'var(--navy-900)' : 'var(--border-default)'), background: on ? 'var(--navy-900)' : 'white', color: on ? 'white' : 'var(--navy-900)', fontSize: 12.5, fontWeight: 600, cursor: 'pointer', fontFamily: 'var(--font-body)', whiteSpace: 'nowrap' }}>{label}</button>;
  const todayKey = new Date().toDateString();
  const isToday = (iso) => !!iso && new Date(iso).toDateString() === todayKey;
  const recent = shown.filter((t) => isToday(t.createdAt) || isToday(t.updatedAt) || (t.history || []).some((h) => isToday(h.at || h.generatedAt || h.date)));
  const renderTplCard = (t) => {
            const cur = CEL.current(t), v = t.versions[t.versions.length - 1];
            return (
              <button key={t.id} type="button" className="ce-card" onClick={() => setDetailsId(t.id)} style={{ textAlign: 'left', background: 'white', border: '1px solid var(--border-default)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-sm)', padding: 12, cursor: 'pointer', display: 'flex', flexDirection: 'column', gap: 12, fontFamily: 'var(--font-body)' }}>
                <CertThumb design={cur} width={250} frame />
                <div style={{ display: 'flex', flexDirection: 'column', gap: 3, padding: '0 2px 2px', flex: 1 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{ flex: 1, minWidth: 0, fontWeight: 700, fontSize: 'var(--text-base)', color: 'var(--text-primary)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{t.name}</span>
                    <span style={{ fontFamily: 'var(--font-mono)', fontSize: 'var(--text-xs)', color: 'var(--text-muted)' }}>v{v.n}</span>
                    <span role="button" tabIndex={0} title={t.favorite ? 'Remove from favourites' : 'Add to favourites'} onClick={(e) => toggleFav(t, e)} onKeyDown={(e) => { if (e.key === 'Enter') toggleFav(t, e); }} style={{ fontSize: 17, lineHeight: 1, color: t.favorite ? '#E8A317' : 'var(--gray-300, #c4cad3)', cursor: 'pointer', padding: '0 2px' }}>★</span>
                  </div>
                  {(CEL.docType(cur) !== 'certificate' || (t.tags || []).length > 0) && <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap', marginTop: 2 }}>
                    {CEL.docType(cur) !== 'certificate' && <span style={{ fontSize: 10.5, fontWeight: 700, padding: '2px 8px', borderRadius: 999, background: 'var(--navy-900)', color: 'white' }}>{CEL.DOC_TYPES[CEL.docType(cur)].label}</span>}
                    {(t.tags || []).map((tg) => <span key={tg} style={{ fontSize: 10.5, fontWeight: 600, padding: '2px 8px', borderRadius: 999, background: 'color-mix(in srgb, var(--brand-primary) 12%, white)', color: 'var(--navy-900)' }}>#{tg}</span>)}
                  </div>}
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 5, marginTop: 6, paddingTop: 8, borderTop: '1px solid var(--border-default)' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 'var(--text-xs)', color: 'var(--text-muted)' }}>
                      <svg width="13" height="13" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" style={{ flexShrink: 0 }}><circle cx="8" cy="8" r="6" /><path d="M8 4.8V8l2.2 1.4" /></svg>
                      <span>Updated <span style={{ color: 'var(--text-secondary)', fontWeight: 600 }}>{certFmt(t.updatedAt)}</span></span>
                    </div>
                    {t.updatedBy && <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 'var(--text-xs)', color: 'var(--text-muted)', minWidth: 0 }}>
                      <span style={{ flexShrink: 0, width: 18, height: 18, borderRadius: '50%', background: 'var(--navy-900)', color: 'white', fontSize: 9, fontWeight: 700, display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>{t.updatedBy.split(' ').filter(Boolean).slice(0, 2).map((w) => w[0]).join('').toUpperCase()}</span>
                      <span style={{ color: 'var(--text-secondary)', fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{t.updatedBy}</span>
                    </div>}
                    {t.history.length > 0 && <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 'var(--text-xs)', color: 'var(--text-muted)' }}>
                      <svg width="13" height="13" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round" style={{ flexShrink: 0 }}><path d="M4.5 6V2.5h7V6M4.5 11H3V7.5h10V11h-1.5M5 9.5h6v4H5z" /></svg>
                      <span>Generated <span style={{ color: 'var(--text-secondary)', fontWeight: 600 }}>{t.history.reduce((s, h) => s + h.count, 0)} {CEL.DOC_TYPES[CEL.docType(cur)].plural}</span></span>
                    </div>}
                  </div>
                </div>
              </button>
            );
          };
  function toggleFav(t, e) { e.stopPropagation(); CEL.setTemplateMeta(t.id, { favorite: !t.favorite }); refresh(); }

  return (
    <div>
      <input ref={pdfInput} type="file" accept="application/pdf,.pdf" style={{ display: 'none' }} onChange={(e) => { onPdf(e.target.files[0]); e.target.value = ''; }} />
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20, flexWrap: 'wrap' }}>
        <window.UdUI.SearchInput value={search} onChange={setSearch} placeholder="Search templates or tags" width={240} />
        <span style={{ flex: 1 }}></span>
        {!isMobile && <Button variant="secondary" onClick={() => pdfInput.current.click()} disabled={!!busy}>{busy || 'Upload PDF template'}</Button>}
        {!isMobile && <Button onClick={() => startNew()}>+ New template</Button>}
      </div>
      {templates.length > 0 && (
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center', marginBottom: 18 }}>
          {[['all', 'All'], ['certificate', 'Certificates'], ['badge', 'Name badges'], ['card', 'Table cards'], ['sign', 'Signs']].map((x) => fpill(typeFilter === x[0], () => setTypeFilter(x[0]), x[1], 'ty' + x[0]))}
          <span style={{ width: 1, height: 20, background: 'var(--border-default)', margin: '0 4px' }}></span>
          {fpill(favOnly, () => setFavOnly((v) => !v), '★ Favourites', 'fav')}
          {allTags.length <= tagLimit ? allTags.map((tg) => fpill(tagFilter === tg, () => setTagFilter(tagFilter === tg ? '' : tg), '#' + tg, 'tag' + tg)) : <CertTagFilter tags={allTags} value={tagFilter} onChange={setTagFilter} />}
          <span style={{ flex: 1 }}></span>
          <div style={{ width: 210 }} title="Who first made the template"><window.CertSelect prefix="Created by: " value={createdBy} onChange={setCreatedBy} options={[{ value: '', label: 'Anyone' }].concat(people('createdBy').map((p) => ({ value: p, label: p })))} /></div>
          <div style={{ width: 210 }} title="Who saved the latest version"><window.CertSelect prefix="Updated by: " value={updatedBy} onChange={setUpdatedBy} options={[{ value: '', label: 'Anyone' }].concat(people('updatedBy').map((p) => ({ value: p, label: p })))} /></div>
          {anyFilter && <button type="button" onClick={() => { setTypeFilter('all'); setFavOnly(false); setTagFilter(''); setCreatedBy(''); setUpdatedBy(''); setSearch(''); }} style={{ border: 'none', background: 'none', color: 'var(--brand-primary)', fontWeight: 700, fontSize: 13, cursor: 'pointer', fontFamily: 'var(--font-body)', padding: '0 4px' }}>Clear filters</button>}
        </div>
      )}
      {isMobile && <div style={{ padding: '12px 14px', borderRadius: 'var(--radius-md)', background: 'var(--bg-sunken)', fontSize: 'var(--text-sm)', color: 'var(--text-secondary)', marginBottom: 16 }}>Designing templates needs a larger screen. On a phone you can still open templates and generate certificates.</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)', marginBottom: 16 }}>{error}</div>}

      {templates.length === 0 ? (
        <div style={{ background: 'white', border: '1px dashed var(--border-strong)', borderRadius: 'var(--radius-lg)', padding: '56px 24px', textAlign: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12 }}>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 'var(--text-xl)' }}>No templates yet</div>
          <div style={{ color: 'var(--text-muted)', fontSize: 'var(--text-sm)', maxWidth: 440 }}>Design a certificate, name badge, table card or sign from scratch, start from a ready-made design, or upload a PDF you already use and place names on it.</div>
          {!isMobile && <div style={{ display: 'flex', gap: 10, marginTop: 6, flexWrap: 'wrap', justifyContent: 'center' }}><Button variant="secondary" onClick={() => pdfInput.current.click()}>Upload PDF template</Button><Button onClick={() => startNew()}>+ New template</Button></div>}
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 28 }}>
          {shown.length === 0 && <div style={{ color: 'var(--text-muted)', fontSize: 'var(--text-sm)' }}>No templates match these filters.</div>}
          {recent.length > 0 && (
            <section>
              <div style={certSecHead}><span>Recent today</span><span style={certSecCount}>{recent.length}</span><span style={{ flex: 1, height: 1, background: 'var(--border-default)' }}></span></div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(250px, 1fr))', gap: 18 }}>{recent.map(renderTplCard)}</div>
            </section>
          )}
          {shown.length > 0 && (
            <section>
              <div style={certSecHead}><span>All templates</span><span style={certSecCount}>{shown.length}</span><span style={{ flex: 1, height: 1, background: 'var(--border-default)' }}></span></div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(250px, 1fr))', gap: 18 }}>{shown.map(renderTplCard)}</div>
            </section>
          )}
        </div>
      )}

      
      <CertStarterPicker open={starterOpen} onClose={() => setStarterOpen(false)} onPick={(s) => openNew(CEL.clone(s.design), s.key === 'blank' ? '' : s.name)} />
      <window.CertPresence show={!!(detailsTpl)}>{detailsTpl && <CertDetails tpl={detailsTpl} isMobile={isMobile} adminName={adminName} onClose={() => setDetailsId(null)} onEdit={openEdit} onGenerate={(tpl, n) => { setDetailsId(null); setGen({ tplId: tpl.id, version: n }); }} onReprint={(tpl, h) => { setDetailsId(null); setGen({ tplId: tpl.id, version: h.version, subId: h.subEventId, reprint: true }); }} onChanged={refresh} />}</window.CertPresence>
      <window.CertPresence show={!!(gen)}>{gen && <window.CertGenerateDialog tpl={templates.find((t) => t.id === gen.tplId)} initialVersion={gen.version} initialSubId={gen.subId} reprint={gen.reprint} adminName={adminName} onClose={() => setGen(null)} onDone={() => { const id = gen.tplId; setGen(null); refresh(); setDetailsId(id); }} />}</window.CertPresence>
      <window.CertPresence show={!!(editor)}>{editor && (
        <window.CertEditor
          initialDesign={editor.design} initialName={editor.name} initialDescription={editor.description}
          isNew={!editor.tplId || !!editor.restored}
          draftKey={editor.tplId || 'new'}
          versionLabel={editingTpl ? 'v' + editingTpl.versions[editingTpl.versions.length - 1].n : 'New template'}
          onSave={onSave}
          onClose={() => { const id = editor.tplId; setEditor(null); refresh(); if (id) setDetailsId(id); }}
        />
      )}</window.CertPresence>
      {window.CertGuideButton && <window.CertGuideButton />}
    </div>
  );
}

window.CertCreatorScreen = CertCreatorScreen;
window.CertModal = CertModal;
