const CE = window.CertEngine;

const certEdStyles = {
  label: { fontSize: 11, fontWeight: 700, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.06em' },
  input: { width: '100%', boxSizing: 'border-box', height: 36, padding: '0 11px', borderRadius: 8, border: '1.5px solid var(--border-default)', fontSize: 13, fontFamily: 'var(--font-body)', background: 'white', color: 'var(--text-primary)', outline: 'none', transition: 'border-color .15s ease, box-shadow .15s ease' },
  section: { display: 'flex', flexDirection: 'column', gap: 12, padding: '16px', borderBottom: '1px solid var(--border-default)' },
  palBtn: { display: 'flex', alignItems: 'center', gap: 10, width: '100%', textAlign: 'left', minHeight: 36, padding: '0 12px', borderRadius: 8, border: '1.5px solid var(--border-default)', background: 'white', cursor: 'pointer', fontSize: 13, fontWeight: 600, color: 'var(--navy-900)', fontFamily: 'var(--font-body)', transition: 'all .15s ease' },
  iconBtn: { minWidth: 36, height: 36, padding: '0 12px', borderRadius: 8, border: '1.5px solid var(--border-default)', background: 'white', cursor: 'pointer', fontSize: 13, fontWeight: 600, color: 'var(--navy-900)', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 6, fontFamily: 'var(--font-body)', whiteSpace: 'nowrap', transition: 'all .15s ease' },
};

function certToHex(v) {
  if (!v) return '#000000';
  if (/^#[0-9a-f]{6}$/i.test(v)) return v;
  if (/^#[0-9a-f]{3}$/i.test(v)) return '#' + v.slice(1).split('').map((c) => c + c).join('');
  const m = /rgba?\((\d+),\s*(\d+),\s*(\d+)/i.exec(v);
  if (m) return '#' + [m[1], m[2], m[3]].map((n) => (+n).toString(16).padStart(2, '0')).join('');
  return '#000000';
}

function CertField({ label, children }) {
  return <label style={{ display: 'flex', flexDirection: 'column', gap: 5, minWidth: 0 }}><span style={certEdStyles.label}>{label}</span>{children}</label>;
}
function CertNum({ value, onChange, step, min, max, unit }) {
  const st = step || 1;
  const v = Math.round((value || 0) * 10) / 10;
  const clamp = (n) => { if (min != null) n = Math.max(min, n); if (max != null) n = Math.min(max, n); return Math.round(n * 100) / 100; };
  return (
    <div className="ce-numwrap" style={{ display: 'flex', alignItems: 'stretch', height: 36, border: '1.5px solid var(--border-default)', borderRadius: 8, background: 'white', overflow: 'hidden', transition: 'border-color .15s ease, box-shadow .15s ease' }}>
      <input className="ce-num" type="number" step={st} min={min} max={max} value={v} onChange={(e) => onChange(clamp(parseFloat(e.target.value) || 0))} style={{ flex: 1, minWidth: 0, border: 'none', outline: 'none', padding: '0 0 0 10px', fontSize: 13, fontFamily: 'var(--font-body)', color: 'var(--text-primary)', background: 'transparent' }} />
      {unit && <span style={{ alignSelf: 'center', fontSize: 11, color: 'var(--text-muted)', padding: '0 6px', fontWeight: 600 }}>{unit}</span>}
      <div style={{ display: 'flex', flexDirection: 'column', borderLeft: '1px solid var(--border-default)' }}>
        <button type="button" tabIndex={-1} className="ce-step" aria-label="Increase" onClick={(e) => { e.preventDefault(); onChange(clamp(v + st)); }} style={{ flex: 1, width: 24, border: 'none', borderBottom: '1px solid var(--border-default)', background: 'var(--bg-sunken)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 0, color: 'var(--navy-900)' }}><svg width="9" height="9" viewBox="0 0 10 10"><path d="M2 6.5l3-3 3 3" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" /></svg></button>
        <button type="button" tabIndex={-1} className="ce-step" aria-label="Decrease" onClick={(e) => { e.preventDefault(); onChange(clamp(v - st)); }} style={{ flex: 1, width: 24, border: 'none', background: 'var(--bg-sunken)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 0, color: 'var(--navy-900)' }}><svg width="9" height="9" viewBox="0 0 10 10"><path d="M2 3.5l3 3 3-3" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" /></svg></button>
      </div>
    </div>
  );
}
function CertSlider({ value, onChange, min, max, step, unit, scale }) {
  const sc = scale || 1;
  const pct = ((value - min) / (max - min)) * 100;
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1fr) 108px', gap: 10, alignItems: 'center' }}>
      <input className="ce-range" type="range" min={min} max={max} step={step} value={value} onChange={(e) => onChange(+e.target.value)} style={{ '--ce-pct': pct + '%' }} />
      <CertNum value={value * sc} min={min * sc} max={max * sc} step={(step || 1) * sc} unit={unit} onChange={(v) => onChange(v / sc)} />
    </div>
  );
}
function CertSelect({ value, onChange, options, fontPreview, placeholder, prefix }) {
  const [open, setOpen] = React.useState(false);
  const [shownList, leavingList] = window.useUdPresence(open, 140);
  const [rect, setRect] = React.useState(null);
  const btnRef = React.useRef(null);
  const listRef = React.useRef(null);
  const cur = options.find((o) => !o.group && o.value === value) || (placeholder ? null : options.find((o) => !o.group));
  React.useEffect(() => {
    if (!open) return;
    const close = (e) => { if (btnRef.current && btnRef.current.contains(e.target)) return; if (listRef.current && listRef.current.contains(e.target)) return; setOpen(false); };
    const off = () => setOpen(false);
    const onScroll = (e) => { if (listRef.current && (e.target === listRef.current || listRef.current.contains(e.target))) return; setOpen(false); };
    document.addEventListener('mousedown', close); window.addEventListener('resize', off); document.addEventListener('scroll', onScroll, true);
    return () => { document.removeEventListener('mousedown', close); window.removeEventListener('resize', off); document.removeEventListener('scroll', onScroll, true); };
  }, [open]);
  function toggle(e) { e.preventDefault(); if (!open) setRect(btnRef.current.getBoundingClientRect()); setOpen((o) => !o); }
  const below = rect ? window.innerHeight - rect.bottom : 0;
  const maxH = 260;
  const up = rect && below < Math.min(maxH, options.length * 38 + 12) + 12 && rect.top > below;
  return (
    <>
      <button ref={btnRef} type="button" onClick={toggle} className="ce-select" style={{ ...certEdStyles.input, display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, cursor: 'pointer', textAlign: 'left', borderColor: open ? 'var(--navy-700)' : 'var(--border-default)', boxShadow: open ? '0 0 0 3px color-mix(in srgb, var(--navy-700) 18%, transparent)' : 'none', fontWeight: 600, fontFamily: fontPreview && cur ? '"' + cur.value + '"' : 'var(--font-body)' }}>
        <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', color: cur ? undefined : 'var(--text-muted)', fontWeight: cur ? undefined : 500 }}>{prefix && <span style={{ fontWeight: 500, color: 'var(--text-muted)' }}>{prefix}</span>}{cur ? cur.label : (placeholder || '')}</span>
        <svg width="12" height="12" viewBox="0 0 12 12" style={{ flexShrink: 0, transform: open ? 'rotate(180deg)' : 'none', transition: 'transform .15s ease', color: 'var(--navy-700)' }}><path d="M2.5 4.5L6 8l3.5-3.5" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" /></svg>
      </button>
      {shownList && rect && ReactDOM.createPortal(
        <div ref={listRef} role="listbox" data-ce-portal="1" className={'ce-pop' + (leavingList ? ' ce-out' : '')} onWheel={(e) => e.stopPropagation()} style={{ position: 'fixed', left: rect.left, width: rect.width, top: up ? undefined : rect.bottom + 6, bottom: up ? window.innerHeight - rect.top + 6 : undefined, maxHeight: maxH, overflowY: 'auto', background: 'white', border: '1px solid var(--border-default)', borderRadius: 10, boxShadow: 'var(--shadow-lg)', zIndex: 2600, padding: 4, animation: 'udPopIn 120ms var(--ease-standard) both' }}>
          {options.length === 0 && <div style={{ padding: '9px 10px', fontSize: 13, color: 'var(--text-muted)' }}>Nothing to choose yet</div>}
          {options.map((o, oi) => {
            if (o.group) return <div key={'g' + oi} style={{ padding: '10px 10px 4px', fontSize: 10, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--text-muted)' }}>{o.label}</div>;
            const on = o.value === value;
            return (
              <div key={o.value} role="option" aria-selected={on} className="ce-opt" onMouseDown={(e) => e.preventDefault()} onClick={() => { onChange(o.value); setOpen(false); }} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, padding: '9px 10px', borderRadius: 7, fontSize: 13, cursor: 'pointer', background: on ? 'color-mix(in srgb, var(--brand-primary) 12%, white)' : undefined, color: on ? 'var(--navy-900)' : 'var(--text-primary)', fontWeight: on ? 700 : 500, fontFamily: fontPreview ? '"' + o.value + '"' : 'var(--font-body)' }}>
                <span>{o.label}</span>
                {on && <svg width="12" height="12" viewBox="0 0 12 12" style={{ color: 'var(--brand-primary)', flexShrink: 0 }}><path d="M2.5 6.2l2.4 2.4L9.5 3.8" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round" /></svg>}
              </div>
            );
          })}
        </div>, document.body)}
    </>
  );
}
function CertCheck({ checked, onChange, disabled, label }) {
  return (
    <label style={{ position: 'relative', display: 'inline-flex', alignItems: 'center', gap: 10, cursor: disabled ? 'not-allowed' : 'pointer', opacity: disabled ? 0.5 : 1, fontSize: 'var(--text-sm)' }}>
      <input type="checkbox" checked={!!checked} disabled={disabled} onChange={(e) => onChange(e.target.checked)} style={{ position: 'absolute', opacity: 0, width: 0, height: 0 }} />
      <span aria-hidden="true" style={{ width: 18, height: 18, flexShrink: 0, borderRadius: 5, border: '1.5px solid ' + (checked ? 'var(--brand-primary)' : 'var(--border-strong, #b9c0c8)'), background: checked ? 'var(--brand-primary)' : 'white', display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'all .12s ease' }}>
        {checked && <svg width="11" height="11" viewBox="0 0 12 12"><path d="M2.5 6.2l2.4 2.4L9.5 3.8" fill="none" stroke="white" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /></svg>}
      </span>
      {label}
    </label>
  );
}
function CertPreviewAttSelect({ atts, onPick }) {
  const [v, setV] = React.useState('');
  return <CertSelect value={v} placeholder={atts ? (atts.length ? 'Choose an attendee' : 'No attendees yet') : 'Loading…'} onChange={(id) => { setV(id); onPick(id); }} options={(atts || []).map((a) => ({ value: a.ticketId, label: a.first + ' ' + a.last }))} />;
}
function CertIcon({ d }) { return <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}><path d={d} /></svg>; }
const CERT_ICONS = {
  up: 'M8 13V3M4 7l4-4 4 4', down: 'M8 3v10M4 9l4 4 4-4', dup: 'M5.5 5.5h7v7h-7zM3.5 10.5v-7h7', lock: 'M4.5 7.5h7v5.5h-7zM6 7.5V5.5a2 2 0 014 0v2', unlock: 'M4.5 7.5h7v5.5h-7zM6 7.5V5.5a2 2 0 013.8-.9', del: 'M3 4.5h10M6.5 4.5V3h3v1.5M4.5 4.5l.6 8.5h5.8l.6-8.5',
  ch: 'M2 8h12M5 5l-3 3 3 3M11 5l3 3-3 3', cv: 'M8 2v12M5 5l3-3 3 3M5 11l3 3 3-3',
  aLeft: 'M2.5 2v12M5 4h8v3H5zM5 9h5v3H5z', aHc: 'M8 2v12M3 4h10v3H3zM5 9h6v3H5z', aRight: 'M13.5 2v12M3 4h8v3H3zM6 9h5v3H6z',
  aTop: 'M2 2.5h12M4 5h3v8H4zM9 5h3v5H9z', aVm: 'M2 8h12M4 3h3v10H4zM9 5h3v6H9z', aBot: 'M2 13.5h12M4 3h3v8H4zM9 6h3v5H9z',
  dH: 'M2 2v12M14 2v12M6 5h4v6H6z', dV: 'M2 2h12M2 14h12M5 6h6v4H5z', front: 'M5 5h8v8H5zM3 3h7v1M3 3v7h1', back: 'M3 3h8v8H3zM13 6v7H6',
  hide: 'M2 8s2.2-4 6-4 6 4 6 4-2.2 4-6 4-6-4-6-4zM3 13L13 3',
};
function CertPalIcon({ k }) {
  const O = 'var(--brand-primary)', N = 'var(--navy-900)';
  let g;
  switch (k) {
    case 'text': g = <text x="16" y="17" textAnchor="middle" fontFamily="Georgia, serif" fontWeight="700" fontSize="14" fill={N}>T</text>; break;
    case 'field': g = <><rect x="4" y="6" width="24" height="12" rx="6" fill="none" stroke={O} strokeWidth="1.5" /><circle cx="10" cy="12" r="2" fill={O} /><path d="M14 12h9" stroke={N} strokeWidth="1.5" strokeLinecap="round" /></>; break;
    case 'image': g = <><rect x="5" y="4" width="22" height="16" rx="2.5" fill="none" stroke={N} strokeWidth="1.5" /><circle cx="11" cy="9.5" r="2" fill={O} /><path d="M6 18l6-6 4 4 3-3 7 6" fill="none" stroke={N} strokeWidth="1.5" strokeLinejoin="round" /></>; break;
    case 'sig': g = <><path d="M5 15c2-6 4-9 5-7s-2 7 0 7 3-5 5-5 1 4 3 4 2-2 4-2 2 1 5 1" fill="none" stroke={N} strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /><path d="M5 19h22" stroke={O} strokeWidth="1.3" strokeLinecap="round" /></>; break;
    case 'udlogo': return <span style={{ width: 32, height: 24, flexShrink: 0, borderRadius: 6, background: 'var(--navy-900)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><img src="assets/tud-logo-white.png" alt="" style={{ maxWidth: 24, maxHeight: 16, objectFit: 'contain' }} /></span>;
    case 'pen': g = <><path d="M20 5l4 4-11 11-5 1 1-5z" fill="none" stroke={N} strokeWidth="1.4" strokeLinejoin="round" /><path d="M5 21c3 0 4-2 7-2" stroke={O} strokeWidth="1.4" strokeLinecap="round" fill="none" /></>; break;
    case 't-head': g = <text x="16" y="17" textAnchor="middle" fontFamily="Georgia, serif" fontWeight="700" fontSize="15" fill={N}>H</text>; break;
    case 't-sub': g = <><path d="M6 10h20" stroke={O} strokeWidth="2.4" strokeLinecap="round" /><path d="M9 15h14" stroke={N} strokeWidth="1.2" strokeLinecap="round" opacity="0.5" /></>; break;
    case 't-para': g = <path d="M6 7h20M6 11h20M6 15h20M6 19h12" stroke={N} strokeWidth="1.3" strokeLinecap="round" />; break;
    case 't-small': g = <path d="M9 12h14" stroke={N} strokeWidth="1" strokeLinecap="round" strokeDasharray="1.5 1.5" />; break;
    case 'lib': g = <><rect x="5" y="6" width="16" height="12" rx="2" fill="none" stroke={N} strokeWidth="1.3" /><rect x="10" y="3.5" width="16" height="12" rx="2" fill="white" stroke={O} strokeWidth="1.3" /><circle cx="15" cy="8" r="1.4" fill={O} /></>; break;
    case 'dline': g = <path d="M5 12h22" stroke={N} strokeWidth="1.8" strokeLinecap="round" strokeDasharray="3 3" />; break;
    case 'line2': g = <path d="M5 10h22M5 14h22" stroke={O} strokeWidth="1.3" strokeLinecap="round" />; break;
    case 'rrect': g = <rect x="6" y="5" width="20" height="14" rx="4" fill="none" stroke={N} strokeWidth="1.5" />; break;
    case 'diamond': g = <path d="M16 3l8 9-8 9-8-9z" fill={O} />; break;
    case 'triangle': g = <path d="M16 4l9 16H7z" fill={N} />; break;
    case 'b-title': g = <><path d="M7 8h18" stroke={N} strokeWidth="2.6" strokeLinecap="round" /><path d="M13 13h6" stroke={O} strokeWidth="1.6" strokeLinecap="round" /><path d="M9 17h14" stroke={N} strokeWidth="1" strokeLinecap="round" opacity="0.5" /></>; break;
    case 'b-dv': g = <><path d="M5 12h9M18 12h9" stroke={N} strokeWidth="1.3" strokeLinecap="round" /><circle cx="16" cy="12" r="1.3" fill={O} /></>; break;
    case 'b-logo': g = <><rect x="11" y="4" width="10" height="7" rx="1.5" fill={N} /><path d="M5 16h22" stroke={O} strokeWidth="1.3" /></>; break;
    case 't-quote': g = <><path d="M6 8h4v4l-2 4M14 8h4v4l-2 4" stroke={N} strokeWidth="1.6" fill="none" strokeLinecap="round" /><path d="M21 12h7" stroke={O} strokeWidth="1.3" /></>; break;
    case 't-script': g = <path d="M4 17c3-9 6-11 7-7s-3 8 0 7 5-8 7-6-1 6 2 5 4-5 7-3" stroke={N} strokeWidth="1.6" fill="none" strokeLinecap="round" />; break;
    case 'b-info': g = <><rect x="4" y="5" width="24" height="14" rx="2" fill="none" stroke={N} strokeWidth="1.3" /><rect x="4" y="5" width="2.4" height="14" fill={O} /><path d="M9 10h12M9 14h16" stroke={N} strokeWidth="1.2" /></>; break;
    case 'b-hours': g = <><circle cx="16" cy="12" r="9" fill={N} stroke={O} strokeWidth="1.3" /><path d="M14 9h3v6" stroke="white" strokeWidth="1.6" fill="none" /></>; break;
    case 'b-person': g = <><path d="M5 7h18" stroke={N} strokeWidth="2.4" /><path d="M5 12h12" stroke={O} strokeWidth="1.6" /><path d="M5 16h15" stroke={N} strokeWidth="1.1" /></>; break;
    case 'd-laurel': g = <><path d="M11 20c-5-3-6-10-3-15M21 20c5-3 6-10 3-15" stroke="#B8892B" strokeWidth="1.4" fill="none" /><path d="M8 8l-2 1M7 12l-2 .5M8 16l-2 0M24 8l2 1M25 12l2 .5M24 16l2 0" stroke="#B8892B" strokeWidth="2" strokeLinecap="round" /></>; break;
    case 'd-stamp': g = <><circle cx="16" cy="12" r="9" fill="none" stroke="#B3261E" strokeWidth="1.6" /><circle cx="16" cy="12" r="6.5" fill="none" stroke="#B3261E" strokeWidth="0.8" /><path d="M11 13l10-3" stroke="#B3261E" strokeWidth="1.6" /></>; break;
    case 'd-shield': g = <path d="M8 4c5-1.5 11-1.5 16 0v8c0 5-4 8-8 10-4-2-8-5-8-10z" fill={N} stroke="#B8892B" strokeWidth="1.3" />; break;
    case 'd-check': g = <><circle cx="16" cy="12" r="9" fill="#1B7A4D" /><path d="M12 12l3 3 5-6" stroke="white" strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round" /></>; break;
    case 'd-heart': g = <path d="M16 21C8 15 6 10 9 7s6-1 7 2c1-3 4-5 7-2s1 8-7 14z" fill="#C2334D" />; break;
    case 'hexagon': g = <path d="M10 4h12l5 8-5 8H10l-5-8z" fill={N} />; break;
    case 'arrow': g = <path d="M4 9h14V5l9 7-9 7v-4H4z" fill={O} />; break;
    case 'd-ribbon': g = <path d="M4 8h24l-3 4 3 4H4l3-4z" fill={N} />; break;
    case 'd-burst': g = <><path d="M16 2l2.2 3.4 3.9-1.2.3 4 3.9 1.1-1.7 3.7 2.6 3-3.6 1.8.2 4-4-.6-1.9 3.5L16 20l-2.1 3.7-1.9-3.5-4 .6.2-4-3.6-1.8 2.6-3L5.5 8.3l3.9-1.1.3-4 3.9 1.2z" fill="#B8892B" /></>; break;
    case 'd-div': g = <><path d="M4 12h9M19 12h9" stroke={O} strokeWidth="1.2" /><path d="M16 9l3 3-3 3-3-3z" fill={O} /></>; break;
    case 'd-star': g = <path d="M16 3.5l2.6 5.6 6.1.7-4.5 4.2 1.2 6-5.4-3-5.4 3 1.2-6-4.5-4.2 6.1-.7z" fill="#B8892B" />; break;
    case 'fr-rounded': g = <rect x="4" y="3" width="24" height="18" rx="4" fill="none" stroke={O} strokeWidth="1.5" />; break;
    case 'fr-triple': g = <><rect x="3" y="2" width="26" height="20" fill="none" stroke={O} strokeWidth="0.9" /><rect x="5.5" y="4.5" width="21" height="15" fill="none" stroke={O} strokeWidth="0.9" /><rect x="8" y="7" width="16" height="10" fill="none" stroke={O} strokeWidth="0.9" /></>; break;
    case 'fr-dashed': g = <rect x="4" y="3" width="24" height="18" fill="none" stroke={O} strokeWidth="1.5" strokeDasharray="3 2" />; break;
    case 'b-sig': g = <><path d="M8 9c1.5-3 3-4 3.5-2.5S10 10 11.5 10s2-3 3.5-3 1 2.5 2.5 2.5" fill="none" stroke={N} strokeWidth="1.2" strokeLinecap="round" /><path d="M7 13h18" stroke={N} strokeWidth="1.2" /><path d="M10 16.5h12M12 19.5h8" stroke={O} strokeWidth="1.4" strokeLinecap="round" /></>; break;
    case 'b-sig2': g = <><path d="M3 12h11M18 12h11" stroke={N} strokeWidth="1.2" /><path d="M4 15.5h9M19 15.5h9" stroke={O} strokeWidth="1.4" strokeLinecap="round" /><path d="M5 18.5h7M20 18.5h7" stroke={N} strokeWidth="1" strokeLinecap="round" opacity="0.5" /></>; break;
    case 'b-seal': g = <><circle cx="16" cy="12" r="9" fill={O} /><circle cx="16" cy="12" r="7" fill="none" stroke="white" strokeWidth="0.9" /><path d="M12.5 12h7" stroke="white" strokeWidth="1.6" strokeLinecap="round" /></>; break;
    case 'b-foot': g = <><rect x="4" y="5" width="24" height="14" rx="1" fill="none" stroke={N} strokeWidth="1" opacity="0.4" /><path d="M6 16h7M19 16h7" stroke={O} strokeWidth="1.6" strokeLinecap="round" /></>; break;
    case 'fr-single': g = <rect x="4" y="3" width="24" height="18" fill="none" stroke={O} strokeWidth="1.5" />; break;
    case 'fr-double': g = <><rect x="3.5" y="2.5" width="25" height="19" fill="none" stroke={O} strokeWidth="1.2" /><rect x="6.5" y="5.5" width="19" height="13" fill="none" stroke={O} strokeWidth="1.2" /></>; break;
    case 'fr-thick-thin': g = <><rect x="4" y="3" width="24" height="18" fill="none" stroke={O} strokeWidth="2.6" /><rect x="7.5" y="6.5" width="17" height="11" fill="none" stroke={O} strokeWidth="0.9" /></>; break;
    case 'fr-corners': g = <path d="M4 8V3h5M23 3h5v5M28 16v5h-5M9 21H4v-5" fill="none" stroke={O} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" />; break;
    case 'fr-dotted': g = <rect x="4" y="3" width="24" height="18" fill="none" stroke={O} strokeWidth="1.6" strokeDasharray="0.1 3" strokeLinecap="round" />; break;
    case 'line': g = <path d="M5 12h22" stroke={O} strokeWidth="2.2" strokeLinecap="round" />; break;
    case 'rect': g = <rect x="6" y="5" width="20" height="14" rx="1.5" fill={N} />; break;
    case 'ellipse': g = <ellipse cx="16" cy="12" rx="9" ry="8" fill={O} />; break;
    default: g = null;
  }
  return <span className="ce-pal-ico" style={{ width: 32, height: 24, flexShrink: 0, borderRadius: 6, background: 'var(--bg-sunken)', display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'background .15s ease' }}><svg width="32" height="24" viewBox="0 0 32 24">{g}</svg></span>;
}
const CertLeaveCtx = React.createContext(false);
function CertPresence({ show, children, ms }) {
  const last = React.useRef(null);
  const [leaving, setLeaving] = React.useState(false);
  const [, bump] = React.useReducer((x) => x + 1, 0);
  if (show) last.current = children;
  React.useEffect(() => {
    if (show) { setLeaving(false); return; }
    if (!last.current) return;
    setLeaving(true);
    const t = setTimeout(() => { last.current = null; setLeaving(false); bump(); }, ms || 220);
    return () => clearTimeout(t);
  }, [show]);
  if (show) return <CertLeaveCtx.Provider value={false}>{children}</CertLeaveCtx.Provider>;
  if (last.current) return <CertLeaveCtx.Provider value={true}>{last.current}</CertLeaveCtx.Provider>;
  return null;
}
function certHexToRgb(h) { h = certToHex(h); return [parseInt(h.slice(1, 3), 16), parseInt(h.slice(3, 5), 16), parseInt(h.slice(5, 7), 16)]; }
function certRgbToHex(r, g, b) { return '#' + [r, g, b].map((n) => Math.max(0, Math.min(255, Math.round(n))).toString(16).padStart(2, '0')).join('').toUpperCase(); }
function certRgbToHsv(r, g, b) { r /= 255; g /= 255; b /= 255; const mx = Math.max(r, g, b), mn = Math.min(r, g, b), d = mx - mn; let h = 0; if (d) { if (mx === r) h = ((g - b) / d) % 6; else if (mx === g) h = (b - r) / d + 2; else h = (r - g) / d + 4; h *= 60; if (h < 0) h += 360; } return [h, mx ? d / mx : 0, mx]; }
function certHsvToRgb(h, s, v) { const c = v * s, x = c * (1 - Math.abs(((h / 60) % 2) - 1)), m = v - c; let r = 0, g = 0, b = 0; if (h < 60) [r, g, b] = [c, x, 0]; else if (h < 120) [r, g, b] = [x, c, 0]; else if (h < 180) [r, g, b] = [0, c, x]; else if (h < 240) [r, g, b] = [0, x, c]; else if (h < 300) [r, g, b] = [x, 0, c]; else [r, g, b] = [c, 0, x]; return [(r + m) * 255, (g + m) * 255, (b + m) * 255]; }
const CERT_SWATCHES = ['#050D1A', '#0E2247', '#173463', '#A8500E', '#EE7F2B', '#F49B52', '#C9A227', '#FFFFFF', '#F4F1EA', '#6B7280', '#000000'];
function certDragArea(e, el, fn) {
  e.preventDefault();
  const r = el.getBoundingClientRect();
  const f = (ev) => fn(Math.min(1, Math.max(0, (ev.clientX - r.left) / r.width)), Math.min(1, Math.max(0, (ev.clientY - r.top) / r.height)));
  f(e);
  const up = () => { window.removeEventListener('pointermove', f); window.removeEventListener('pointerup', up); };
  window.addEventListener('pointermove', f); window.addEventListener('pointerup', up);
}
function CertColor({ value, onChange }) {
  const [open, setOpen] = React.useState(false);
  const [out, setOut] = React.useState(false);
  const [rect, setRect] = React.useState(null);
  const [hsv, setHsv] = React.useState([0, 0, 0]);
  const [hexDraft, setHexDraft] = React.useState('');
  const [popH, setPopH] = React.useState(0);
  React.useLayoutEffect(() => { if (open && popRef.current) { const h = popRef.current.offsetHeight; if (h && Math.abs(h - popH) > 1) setPopH(h); } });
  const btnRef = React.useRef(null), popRef = React.useRef(null), svRef = React.useRef(null), hueRef = React.useRef(null);
  const hex = certToHex(value).toUpperCase();
  function show() { const rgb = certHexToRgb(value); setHsv(certRgbToHsv(rgb[0], rgb[1], rgb[2])); setHexDraft(hex); setRect(btnRef.current.getBoundingClientRect()); setOut(false); setOpen(true); }
  function hide() { if (!open || out) return; setOut(true); setTimeout(() => { setOpen(false); setOut(false); }, 150); }
  React.useEffect(() => {
    if (!open) return;
    const down = (e) => { if (popRef.current && popRef.current.contains(e.target)) return; if (btnRef.current && btnRef.current.contains(e.target)) return; hide(); };
    const key = (e) => { if (e.key === 'Escape') { e.stopPropagation(); hide(); } };
    document.addEventListener('mousedown', down); document.addEventListener('keydown', key, true);
    return () => { document.removeEventListener('mousedown', down); document.removeEventListener('keydown', key, true); };
  });
  function setFromHsv(n) { setHsv(n); const rgb = certHsvToRgb(n[0], n[1], n[2]); const hx = certRgbToHex(rgb[0], rgb[1], rgb[2]); setHexDraft(hx); onChange(hx); }
  function setFromHex(hx) { const rgb = certHexToRgb(hx); setHsv(certRgbToHsv(rgb[0], rgb[1], rgb[2])); setHexDraft(hx.toUpperCase()); onChange(hx.toUpperCase()); }
  async function eyedrop() { try { const r = await new window.EyeDropper().open(); setFromHex(r.sRGBHex); } catch (e) {} }
  const rgbNow = certHexToRgb(hex);
  const pureHue = certRgbToHex.apply(null, certHsvToRgb(hsv[0], 1, 1));
  let pos = null;
  if (rect) {
    const W = 260, Hh = popH || 350, vh = window.innerHeight, left = Math.max(8, Math.min(rect.left, window.innerWidth - W - 8));
    if (vh - rect.bottom >= Hh + 14) pos = { left, top: rect.bottom + 6, origin: 'top left' };
    else if (rect.top >= Hh + 14) pos = { left, top: rect.top - Hh - 6, origin: 'bottom left' };
    else pos = { left, top: Math.max(8, Math.min(rect.bottom + 6, vh - Hh - 8)), origin: 'top left' };
  }
  const chan = (i, label) => (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 3, alignItems: 'center', minWidth: 0 }}>
      <input className="ce-input" type="number" min="0" max="255" value={rgbNow[i]} onChange={(e) => { const c = rgbNow.slice(); c[i] = Math.max(0, Math.min(255, +e.target.value || 0)); setFromHex(certRgbToHex(c[0], c[1], c[2])); }} style={{ ...certEdStyles.input, height: 32, padding: '0 6px', textAlign: 'center' }} />
      <span style={{ fontSize: 10, fontWeight: 700, color: 'var(--text-muted)' }}>{label}</span>
    </label>
  );
  return (
    <div style={{ display: 'flex', gap: 6 }}>
      <button ref={btnRef} type="button" className="ce-swatch" aria-label="Choose color" onClick={(e) => { e.preventDefault(); open ? hide() : show(); }} style={{ position: 'relative', width: 36, height: 36, flexShrink: 0, borderRadius: 8, border: '1.5px solid ' + (open ? 'var(--navy-700)' : 'var(--border-default)'), background: value || '#000', cursor: 'pointer', boxShadow: 'inset 0 0 0 2px white' + (open ? ', 0 0 0 3px color-mix(in srgb, var(--navy-700) 18%, transparent)' : ''), padding: 0 }}></button>
      <input className="ce-input" value={value || ''} onChange={(e) => onChange(e.target.value)} style={{ ...certEdStyles.input, fontFamily: 'var(--font-mono)', fontSize: 12 }} />
      {open && pos && ReactDOM.createPortal(
        <div ref={popRef} data-ce-portal="1" className={'ce-pop' + (out ? ' ce-out' : '')} onMouseDown={(e) => e.stopPropagation()} style={{ position: 'fixed', left: pos.left, top: pos.top, transformOrigin: pos.origin, maxHeight: 'calc(100vh - 16px)', overflowY: 'auto', width: 260, boxSizing: 'border-box', background: 'white', border: '1px solid var(--border-default)', borderRadius: 14, boxShadow: '0 18px 40px rgba(5,13,26,.22)', zIndex: 2600, padding: 12, display: 'flex', flexDirection: 'column', gap: 12, fontFamily: 'var(--font-body)' }}>
          <div ref={svRef} onPointerDown={(e) => certDragArea(e, svRef.current, (x, y) => setFromHsv([hsv[0], x, 1 - y]))} style={{ position: 'relative', height: 150, borderRadius: 10, cursor: 'crosshair', background: 'linear-gradient(to top, #000, transparent), linear-gradient(to right, #fff, transparent), ' + pureHue, touchAction: 'none' }}>
            <span style={{ position: 'absolute', left: (hsv[1] * 100) + '%', top: ((1 - hsv[2]) * 100) + '%', width: 16, height: 16, marginLeft: -8, marginTop: -8, borderRadius: '50%', border: '2.5px solid white', boxShadow: '0 0 0 1px rgba(0,0,0,.35), 0 2px 4px rgba(0,0,0,.3)', background: hex, pointerEvents: 'none' }}></span>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            {window.EyeDropper && <button type="button" className="ce-btn" title="Pick a color from the screen" onClick={eyedrop} style={{ ...certEdStyles.iconBtn, minWidth: 32, width: 32, height: 32, padding: 0 }}><CertIcon d="M10.5 2.5l3 3-1.5 1.5-3-3zM9 4l3 3-6 6H3v-3z" /></button>}
            <span style={{ width: 28, height: 28, borderRadius: '50%', background: hex, boxShadow: 'inset 0 0 0 1px rgba(0,0,0,.12)', flexShrink: 0 }}></span>
            <div ref={hueRef} onPointerDown={(e) => certDragArea(e, hueRef.current, (x) => setFromHsv([Math.min(359.9, x * 360), hsv[1], hsv[2]]))} style={{ position: 'relative', flex: 1, height: 12, borderRadius: 999, cursor: 'pointer', background: 'linear-gradient(to right, #f00 0%, #ff0 17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%)', touchAction: 'none' }}>
              <span style={{ position: 'absolute', top: '50%', left: (hsv[0] / 360 * 100) + '%', width: 18, height: 18, marginLeft: -9, marginTop: -9, borderRadius: '50%', background: pureHue, border: '3px solid white', boxShadow: '0 0 0 1px rgba(0,0,0,.25), 0 2px 4px rgba(0,0,0,.25)', pointerEvents: 'none' }}></span>
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr 1fr 1fr', gap: 6 }}>
            <label style={{ display: 'flex', flexDirection: 'column', gap: 3, alignItems: 'center', minWidth: 0 }}>
              <input className="ce-input" value={hexDraft} onChange={(e) => { const v = e.target.value; setHexDraft(v); if (/^#?[0-9a-f]{6}$/i.test(v.trim())) setFromHex(v.trim()[0] === '#' ? v.trim() : '#' + v.trim()); }} style={{ ...certEdStyles.input, height: 32, padding: '0 8px', fontFamily: 'var(--font-mono)', fontSize: 12, textAlign: 'center' }} />
              <span style={{ fontSize: 10, fontWeight: 700, color: 'var(--text-muted)' }}>HEX</span>
            </label>
            {chan(0, 'R')}{chan(1, 'G')}{chan(2, 'B')}
          </div>
          <div style={{ borderTop: '1px solid var(--border-default)', paddingTop: 10, display: 'flex', flexDirection: 'column', gap: 8 }}>
            <span style={certEdStyles.label}>Brand colors</span>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(11, 1fr)', gap: 4 }}>
              {CERT_SWATCHES.map((c) => <button key={c} type="button" title={c} onClick={() => setFromHex(c)} className="ce-sw" style={{ aspectRatio: '1', borderRadius: 6, border: hex === c ? '2px solid var(--brand-primary)' : '1px solid rgba(0,0,0,.12)', background: c, cursor: 'pointer', padding: 0 }}></button>)}
            </div>
          </div>
        </div>, document.body)}
    </div>
  );
}
function CertToggle({ label, checked, onChange }) {
  return (
    <label style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 10, fontSize: 13, cursor: 'pointer', color: 'var(--text-primary)' }}>
      <input type="checkbox" checked={!!checked} onChange={(e) => onChange(e.target.checked)} style={{ position: 'absolute', opacity: 0, width: 0, height: 0 }} /><span aria-hidden="true" style={{ position: 'relative', width: 34, height: 20, borderRadius: 999, background: checked ? 'var(--brand-primary)' : 'var(--gray-300, #cfd4da)', transition: 'background .15s ease', flexShrink: 0 }}><span style={{ position: 'absolute', top: 2, left: checked ? 16 : 2, width: 16, height: 16, borderRadius: '50%', background: 'white', boxShadow: '0 1px 2px rgba(0,0,0,.25)', transition: 'left .15s ease' }}></span></span><span style={{ fontWeight: 500 }}>{label}</span>
    </label>
  );
}
function CertSeg({ value, options, onChange }) {
  return (
    <div style={{ display: 'flex', gap: 2, padding: 3, background: 'var(--bg-sunken)', border: '1px solid var(--border-default)', borderRadius: 9 }}>
      {options.map((o) => (
        <button key={o.value} type="button" onClick={() => onChange(o.value)} style={{ flex: '1 1 auto', minWidth: 0, height: 30, padding: '0 10px', border: 'none', borderRadius: 6, background: value === o.value ? 'var(--navy-900)' : 'transparent', color: value === o.value ? 'white' : 'var(--navy-900)', fontSize: 12, cursor: 'pointer', fontWeight: 600, fontFamily: 'var(--font-body)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', boxShadow: value === o.value ? '0 1px 2px rgba(5,13,26,.25)' : 'none', transition: 'all .15s ease' }}>{o.label}</button>
      ))}
    </div>
  );
}

function CertMenuButton({ label, children, width, dark, title, icon, onOpen, triggerStyle, labelClass }) {
  const [open, setOpen] = React.useState(false);
  const [out, setOut] = React.useState(false);
  const [pos, setPos] = React.useState(null);
  const btnRef = React.useRef(null), panelRef = React.useRef(null);
  function show() { const r = btnRef.current.getBoundingClientRect(), W = width || 260; setPos({ left: Math.max(8, Math.min(r.right - W, window.innerWidth - W - 8)), top: r.bottom + 6, w: W }); setOut(false); setOpen(true); if (onOpen) onOpen(); }
  function hide() { if (!open) return; setOut(true); setTimeout(() => { setOpen(false); setOut(false); }, 140); }
  React.useEffect(() => {
    if (!open) return;
    const down = (e) => { if (btnRef.current && btnRef.current.contains(e.target)) return; if (panelRef.current && panelRef.current.contains(e.target)) return; if (e.target.closest && e.target.closest('[data-ce-portal]')) return; hide(); };
    const key = (e) => { if (e.key === 'Escape') hide(); };
    document.addEventListener('mousedown', down); document.addEventListener('keydown', key);
    return () => { document.removeEventListener('mousedown', down); document.removeEventListener('keydown', key); };
  });
  return (
    <>
      <button ref={btnRef} type="button" title={title} onClick={() => (open ? hide() : show())} style={{ ...certEdStyles.iconBtn, height: 34, flexShrink: 0, maxWidth: 240, background: dark ? 'transparent' : (open ? 'var(--bg-sunken)' : 'white'), color: dark ? 'white' : 'var(--navy-900)', borderColor: dark ? 'rgba(255,255,255,0.25)' : 'var(--border-default)', ...(triggerStyle || {}) }}>{icon}{label ? <span className={labelClass} style={{ minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{label}</span> : null}<svg width="10" height="10" viewBox="0 0 12 12" style={{ flexShrink: 0, transform: open ? 'rotate(180deg)' : 'none', transition: 'transform .15s ease' }}><path d="M2.5 4.5L6 8l3.5-3.5" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" /></svg></button>
      {open && pos && ReactDOM.createPortal(
        <div ref={panelRef} data-ce-portal="1" className={'ce-pop' + (out ? ' ce-out' : '')} style={{ position: 'fixed', left: pos.left, top: pos.top, width: pos.w, maxHeight: 'calc(100vh - ' + (pos.top + 12) + 'px)', overflowY: 'auto', zIndex: 2600, background: 'white', color: 'var(--text-primary)', border: '1px solid var(--border-default)', borderRadius: 12, boxShadow: '0 16px 36px rgba(5,13,26,.24)', padding: 12, display: 'flex', flexDirection: 'column', gap: 10, transformOrigin: 'top right', fontFamily: 'var(--font-body)' }}>
          {typeof children === 'function' ? children(hide) : children}
        </div>, document.body)}
    </>
  );
}
const CERT_SHORTCUTS = [
  ['Ctrl + S', 'Save'], ['Ctrl + Z', 'Undo'], ['Ctrl + Shift + Z  or  Ctrl + Y', 'Redo'], ['Ctrl + C / Ctrl + V', 'Copy / paste elements'], ['Ctrl + Alt + C / Ctrl + Alt + V', 'Copy / paste style'],
  ['Ctrl + D', 'Duplicate'], ['Delete', 'Delete selected'], ['Ctrl + A', 'Select everything'], ['Ctrl + G / Ctrl + Shift + G', 'Group / ungroup'], ['Arrow keys', 'Nudge 1 pt (hold Shift for 10)'],
  ['Shift + click', 'Add to / remove from selection'], ['Drag on empty space', 'Select by drawing a box'], ['Alt + click', 'Pick one item inside a group'], ['Alt while dragging', 'Place freely (no snapping)'],
  ['Shift while resizing', 'Keep proportions'], ['Shift while rotating', 'Snap to 15°'], ['Double-click text', 'Edit the wording'], ['Right-click', 'More options'], ['?', 'Show this list'],
];
window.CERT_SHORTCUTS = CERT_SHORTCUTS;
function CertCropDialog({ el, onApply, onClose }) {
  const src = CE.srcOf(el.src);
  const [c, setC] = React.useState(el.crop || { x: 0, y: 0, w: 1, h: 1 });
  const [nat, setNat] = React.useState(null);
  const boxRef = React.useRef(null);
  const ratio = nat ? nat.w / nat.h : 1, maxW = 560, maxH = 380;
  const dispW = nat ? Math.min(maxW, maxH * ratio) : maxW, dispH = nat ? dispW / ratio : maxH;
  function drag(e, mode) {
    e.preventDefault(); e.stopPropagation();
    const r = boxRef.current.getBoundingClientRect(), sx = e.clientX, sy = e.clientY, o = { ...c };
    const mv = (ev) => {
      const dx = (ev.clientX - sx) / r.width, dy = (ev.clientY - sy) / r.height, n = { ...o }, MIN = 0.05;
      if (mode === 'move') { n.x = Math.min(1 - o.w, Math.max(0, o.x + dx)); n.y = Math.min(1 - o.h, Math.max(0, o.y + dy)); }
      else {
        if (mode.indexOf('e') !== -1) n.w = Math.min(1 - o.x, Math.max(MIN, o.w + dx));
        if (mode.indexOf('s') !== -1) n.h = Math.min(1 - o.y, Math.max(MIN, o.h + dy));
        if (mode.indexOf('w') !== -1) { const nx = Math.min(o.x + o.w - MIN, Math.max(0, o.x + dx)); n.w = o.w + (o.x - nx); n.x = nx; }
        if (mode.indexOf('n') !== -1) { const ny = Math.min(o.y + o.h - MIN, Math.max(0, o.y + dy)); n.h = o.h + (o.y - ny); n.y = ny; }
      }
      setC(n);
    };
    const up = () => { window.removeEventListener('pointermove', mv); window.removeEventListener('pointerup', up); };
    window.addEventListener('pointermove', mv); window.addEventListener('pointerup', up);
  }
  function preset(kind) {
    if (kind === 'free' || !nat) { setC({ x: 0, y: 0, w: 1, h: 1 }); return; }
    const target = kind === 'square' ? 1 : el.w / el.h, imgR = nat.w / nat.h;
    let w = 1, h = 1; if (imgR > target) w = target / imgR; else h = imgR / target;
    setC({ x: (1 - w) / 2, y: (1 - h) / 2, w, h });
  }
  const btn = { ...certEdStyles.iconBtn };
  return ReactDOM.createPortal(
    <div className="ce-modal-bd" onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 2400, background: 'rgba(8,21,27,0.6)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16, fontFamily: 'var(--font-body)' }}>
      <div className="ce-modal-panel" onClick={(e) => e.stopPropagation()} style={{ background: 'white', borderRadius: 14, boxShadow: 'var(--shadow-lg)', padding: 20, display: 'flex', flexDirection: 'column', gap: 14, maxWidth: '100%' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 18, flex: 1 }}>Crop image</div>
          <div style={{ display: 'flex', gap: 6 }}><button type="button" className="ce-btn" style={btn} onClick={() => preset('free')}>Whole image</button><button type="button" className="ce-btn" style={btn} onClick={() => preset('square')}>Square</button><button type="button" className="ce-btn" style={btn} onClick={() => preset('box')}>Fit the box</button></div>
        </div>
        <div ref={boxRef} style={{ position: 'relative', width: dispW, height: dispH, background: 'repeating-conic-gradient(#eee 0 25%, #fff 0 50%) 0 0/16px 16px', userSelect: 'none', touchAction: 'none' }}>
          <img src={src} alt="" draggable={false} onLoad={(e) => setNat({ w: e.target.naturalWidth, h: e.target.naturalHeight })} style={{ width: '100%', height: '100%', display: 'block', pointerEvents: 'none' }} />
          <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', background: 'rgba(5,13,26,.55)', clipPath: 'polygon(0 0, 100% 0, 100% 100%, 0 100%, 0 0, ' + (c.x * 100) + '% ' + (c.y * 100) + '%, ' + (c.x * 100) + '% ' + ((c.y + c.h) * 100) + '%, ' + ((c.x + c.w) * 100) + '% ' + ((c.y + c.h) * 100) + '%, ' + ((c.x + c.w) * 100) + '% ' + (c.y * 100) + '%, ' + (c.x * 100) + '% ' + (c.y * 100) + '%)' }}></div>
          <div onPointerDown={(e) => drag(e, 'move')} style={{ position: 'absolute', left: c.x * 100 + '%', top: c.y * 100 + '%', width: c.w * 100 + '%', height: c.h * 100 + '%', border: '2px solid white', boxShadow: '0 0 0 1px rgba(0,0,0,.4)', cursor: 'move' }}>
            {['nw', 'ne', 'se', 'sw', 'n', 'e', 's', 'w'].map((h) => <div key={h} onPointerDown={(e) => drag(e, h)} style={{ position: 'absolute', left: certHandlePos[h][0] * 100 + '%', top: certHandlePos[h][1] * 100 + '%', width: 12, height: 12, marginLeft: -6, marginTop: -6, background: 'var(--brand-primary)', border: '2px solid white', borderRadius: 3, cursor: certHandleCursor[h] }}></div>)}
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
          <button type="button" className="ce-btn" style={btn} onClick={onClose}>Cancel</button>
          <button type="button" style={{ ...btn, background: 'var(--brand-primary)', borderColor: 'var(--brand-primary)', color: 'white' }} onClick={() => onApply(c.x < 0.001 && c.y < 0.001 && c.w > 0.999 && c.h > 0.999 ? null : c)}>Apply crop</button>
        </div>
      </div>
    </div>, document.body);
}
function CertSaveWithNote({ busy, onSave }) {
  const [note, setNote] = React.useState('');
  return (
    <div style={{ display: 'flex', flexShrink: 0 }}>
      <button type="button" onClick={() => { onSave(''); }} disabled={busy} style={{ ...certEdStyles.iconBtn, height: 34, whiteSpace: 'nowrap', background: 'var(--brand-primary)', borderColor: 'var(--brand-primary)', color: 'white', fontWeight: 700, borderTopRightRadius: 0, borderBottomRightRadius: 0 }}><span className="ce-long">Save new version</span><span className="ce-short">Save</span></button>
      <CertMenuButton dark width={300} title="Save with a note" label="" icon={null} triggerStyle={{ width: 30, minWidth: 30, padding: 0, background: 'var(--brand-primary)', borderColor: 'var(--brand-primary)', borderLeft: '1px solid rgba(255,255,255,0.45)', borderTopLeftRadius: 0, borderBottomLeftRadius: 0, color: 'white', gap: 0 }}>
        {(hide) => (<>
          <span style={certEdStyles.label}>What changed? (optional)</span>
          <input className="ce-input" autoFocus value={note} onChange={(e) => setNote(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') { onSave(note); setNote(''); hide(); } }} placeholder="e.g. Fixed the coach's name" style={certEdStyles.input} />
          <div style={{ fontSize: 11.5, color: 'var(--text-muted)' }}>The note shows in the version list, so it's easy to find this version later.</div>
          <button type="button" disabled={busy} onClick={() => { onSave(note); setNote(''); hide(); }} style={{ ...certEdStyles.iconBtn, background: 'var(--brand-primary)', borderColor: 'var(--brand-primary)', color: 'white', fontWeight: 700 }}>Save with note</button>
        </>)}
      </CertMenuButton>
    </div>
  );
}
function CertSignaturePad({ onSave, onClose }) {
  const ref = React.useRef(null), ctxRef = React.useRef(null), drawing = React.useRef(false), last = React.useRef(null), inked = React.useRef(false);
  const [color, setColor] = React.useState('#0E2247');
  const [width, setWidth] = React.useState(3);
  const [has, setHas] = React.useState(false);
  React.useEffect(() => { const c = ref.current, dpr = window.devicePixelRatio || 1; c.width = 640 * dpr; c.height = 240 * dpr; const x = c.getContext('2d'); x.scale(dpr, dpr); x.lineCap = 'round'; x.lineJoin = 'round'; ctxRef.current = x; }, []);
  function pt(e) { const r = ref.current.getBoundingClientRect(); return { x: (e.clientX - r.left) * 640 / r.width, y: (e.clientY - r.top) * 240 / r.height }; }
  function down(e) { e.preventDefault(); ref.current.setPointerCapture(e.pointerId); drawing.current = true; last.current = pt(e); const x = ctxRef.current; x.fillStyle = color; x.beginPath(); x.arc(last.current.x, last.current.y, width / 2, 0, Math.PI * 2); x.fill(); inked.current = true; setHas(true); }
  function move(e) {
    if (!drawing.current) return; const p = pt(e), l = last.current, x = ctxRef.current;
    const dist = Math.hypot(p.x - l.x, p.y - l.y), w = Math.max(width * 0.55, width * (1.25 - Math.min(dist, 30) / 40));
    x.strokeStyle = color; x.lineWidth = w; x.beginPath(); x.moveTo(l.x, l.y); x.quadraticCurveTo(l.x, l.y, (l.x + p.x) / 2, (l.y + p.y) / 2); x.lineTo(p.x, p.y); x.stroke(); last.current = p;
  }
  function up() { drawing.current = false; }
  function clear() { const c = ref.current; ctxRef.current.clearRect(0, 0, c.width, c.height); inked.current = false; setHas(false); }
  function done() {
    const c = ref.current, x = c.getContext('2d'), d = x.getImageData(0, 0, c.width, c.height).data; let x0 = c.width, y0 = c.height, x1 = 0, y1 = 0;
    for (let yy = 0; yy < c.height; yy += 2) for (let xx = 0; xx < c.width; xx += 2) { if (d[(yy * c.width + xx) * 4 + 3] > 10) { if (xx < x0) x0 = xx; if (yy < y0) y0 = yy; if (xx > x1) x1 = xx; if (yy > y1) y1 = yy; } }
    if (x1 <= x0) return; const pad = 12; x0 = Math.max(0, x0 - pad); y0 = Math.max(0, y0 - pad); x1 = Math.min(c.width, x1 + pad); y1 = Math.min(c.height, y1 + pad);
    const o = document.createElement('canvas'); o.width = x1 - x0; o.height = y1 - y0; o.getContext('2d').drawImage(c, x0, y0, o.width, o.height, 0, 0, o.width, o.height);
    onSave(o.toDataURL('image/png'), o.width / o.height);
  }
  const btn = certEdStyles.iconBtn;
  return ReactDOM.createPortal(
    <div className="ce-modal-bd" onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 2400, background: 'rgba(8,21,27,0.6)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16, fontFamily: 'var(--font-body)' }}>
      <div className="ce-modal-panel" onClick={(e) => e.stopPropagation()} style={{ width: 'min(700px, 100%)', background: 'white', borderRadius: 14, boxShadow: 'var(--shadow-lg)', padding: 20, display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 18 }}>Draw a signature</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0,1.4fr) minmax(0,1fr)', gap: 16, alignItems: 'end' }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <span style={certEdStyles.label}>Ink colour</span>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
              {['#0E2247', '#000000', '#1D4ED8', '#0F5132', '#7A1F2B', '#A8500E', '#B8892B', '#4B5563'].map((cc) => <button key={cc} type="button" title={cc} aria-label={'Ink ' + cc} onClick={() => setColor(cc)} style={{ width: 26, height: 26, borderRadius: '50%', background: cc, border: color.toUpperCase() === cc.toUpperCase() ? '3px solid var(--brand-primary)' : '2px solid white', boxShadow: '0 0 0 1px rgba(0,0,0,.2)', cursor: 'pointer', padding: 0 }}></button>)}
              <div style={{ width: 150 }}><CertColor value={color} onChange={(v) => { if (/^#[0-9a-f]{6}$/i.test(v)) setColor(v); }} /></div>
            </div>
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <span style={certEdStyles.label}>Pen thickness</span>
            <CertSeg value={width} options={[{ value: 2, label: 'Thin' }, { value: 3, label: 'Medium' }, { value: 5, label: 'Bold' }, { value: 7, label: 'Extra bold' }]} onChange={setWidth} />
          </div>
        </div>
        <div style={{ position: 'relative', border: '1.5px solid var(--border-default)', borderRadius: 10, background: 'white' }}>
          <canvas ref={ref} onPointerDown={down} onPointerMove={move} onPointerUp={up} onPointerCancel={up} style={{ width: '100%', aspectRatio: '640 / 240', display: 'block', touchAction: 'none', cursor: 'crosshair' }}></canvas>
          <div style={{ position: 'absolute', left: 30, right: 30, bottom: 50, borderTop: '1px dashed #c4cad3', pointerEvents: 'none' }}></div>
          {!has && <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--text-muted)', fontSize: 14, pointerEvents: 'none' }}>Sign here with your mouse, finger or stylus</div>}
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <button type="button" className="ce-btn" style={btn} onClick={clear}>Clear</button>
          <span style={{ flex: 1 }}></span>
          <button type="button" className="ce-btn" style={btn} onClick={onClose}>Cancel</button>
          <button type="button" disabled={!has} onClick={done} style={{ ...btn, background: 'var(--brand-primary)', borderColor: 'var(--brand-primary)', color: 'white', opacity: has ? 1 : 0.5 }}>Use this signature</button>
        </div>
      </div>
    </div>, document.body);
}
function CertHelpDialog({ onClose }) {
  React.useEffect(() => { const k = (e) => { if (e.key === 'Escape') onClose(); }; window.addEventListener('keydown', k); return () => window.removeEventListener('keydown', k); }, []);
  return ReactDOM.createPortal(
    <div className="ce-modal-bd" onClick={onClose} style={{ position: 'fixed', inset: 0, zIndex: 2400, background: 'rgba(8,21,27,0.6)', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16, fontFamily: 'var(--font-body)' }}>
      <div className="ce-modal-panel" onClick={(e) => e.stopPropagation()} style={{ width: 'min(720px, 100%)', maxHeight: '86vh', overflowY: 'auto', background: 'white', borderRadius: 14, boxShadow: 'var(--shadow-lg)', padding: 22 }}>
        <div style={{ display: 'flex', alignItems: 'center', marginBottom: 14 }}>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 18, flex: 1 }}>Keyboard & mouse shortcuts</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 }}>×</button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))', columnGap: 24 }}>
          {CERT_SHORTCUTS.map((r) => (
            <div key={r[0]} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '8px 0', borderBottom: '1px solid var(--border-default)' }}>
              <span style={{ flex: 1, fontSize: 13 }}>{r[1]}</span>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11.5, background: 'var(--bg-sunken)', border: '1px solid var(--border-default)', borderRadius: 6, padding: '3px 7px', whiteSpace: 'nowrap', color: 'var(--navy-900)' }}>{r[0]}</span>
            </div>
          ))}
        </div>
        <div style={{ fontSize: 11.5, color: 'var(--text-muted)', marginTop: 12 }}>On a Mac, use Cmd instead of Ctrl, and Option instead of Alt.</div>
      </div>
    </div>, document.body);
}
function CertRuler({ len, zoom, axis }) {
  const mmLen = len / CE.MM, px = len * zoom, major = 10 * CE.MM * zoom >= 26 ? 10 : 20, ticks = [];
  for (let m = 0; m <= mmLen; m += 5) {
    const pos = m * CE.MM * zoom, isMaj = m % major === 0, sz = isMaj ? 9 : 4;
    ticks.push(axis === 'x' ? <line key={m} x1={pos} y1={20 - sz} x2={pos} y2={20} stroke="#7A8699" strokeWidth="1" /> : <line key={m} y1={pos} x1={20 - sz} y2={pos} x2={20} stroke="#7A8699" strokeWidth="1" />);
    if (isMaj && m > 0) ticks.push(axis === 'x' ? <text key={'t' + m} x={pos + 2} y={9} fontSize="8.5" fill="#56627A" fontFamily="IBM Plex Mono, monospace">{m}</text> : <text key={'t' + m} x={2} y={pos - 2} fontSize="8.5" fill="#56627A" fontFamily="IBM Plex Mono, monospace">{m}</text>);
  }
  const box = axis === 'x' ? { left: 0, top: -22, width: px, height: 20 } : { top: 0, left: -22, width: 20, height: px };
  return <svg width={box.width} height={box.height} style={{ position: 'absolute', ...box, background: 'white', borderRadius: 3, boxShadow: '0 0 0 1px var(--border-default)', pointerEvents: 'none', overflow: 'visible' }}>{ticks}</svg>;
}
function CertCtxMenu({ menu, onClose, act, count, locked, gridOn, rulersOn, grouped }) {
  const ref = React.useRef(null);
  const [pos, setPos] = React.useState({ left: menu.x, top: menu.y });
  React.useLayoutEffect(() => { const el = ref.current; if (!el) return; const w = el.offsetWidth, h = el.offsetHeight; setPos({ left: Math.max(8, Math.min(menu.x, window.innerWidth - w - 8)), top: Math.max(8, Math.min(menu.y, window.innerHeight - h - 8)) }); }, [menu.x, menu.y]);
  React.useEffect(() => {
    const down = (e) => { if (ref.current && !ref.current.contains(e.target)) onClose(); };
    const off = () => onClose();
    document.addEventListener('mousedown', down); window.addEventListener('blur', off); window.addEventListener('resize', off);
    return () => { document.removeEventListener('mousedown', down); window.removeEventListener('blur', off); window.removeEventListener('resize', off); };
  }, []);
  const item = (a, label, icon, kbd, danger) => (
    <button key={a} type="button" className="ce-ctx-item" onClick={() => act(a)} style={{ display: 'flex', alignItems: 'center', gap: 10, width: '100%', height: 32, padding: '0 10px', border: 'none', borderRadius: 6, background: 'transparent', cursor: 'pointer', fontSize: 13, fontWeight: 500, color: danger ? 'var(--status-error)' : 'var(--navy-900)', fontFamily: 'var(--font-body)', textAlign: 'left' }}>
      <span style={{ width: 16, display: 'flex', justifyContent: 'center' }}>{icon && <CertIcon d={icon} />}</span>
      <span style={{ flex: 1 }}>{label}</span>
      {kbd && <span style={{ fontSize: 11, color: 'var(--text-muted)', fontFamily: 'var(--font-mono)' }}>{kbd}</span>}
    </button>
  );
  const sep = (k) => <div key={k} style={{ height: 1, background: 'var(--border-default)', margin: '4px 6px' }}></div>;
  return ReactDOM.createPortal(
    <div ref={ref} className="ce-pop" onContextMenu={(e) => e.preventDefault()} style={{ position: 'fixed', left: pos.left, top: pos.top, zIndex: 2300, width: 236, maxHeight: 'calc(100vh - 16px)', overflowY: 'auto', background: 'white', border: '1px solid var(--border-default)', borderRadius: 10, boxShadow: '0 14px 34px rgba(5,13,26,.22)', padding: 4, transformOrigin: 'top left' }}>
      {menu.empty ? <>
        {item('paste', 'Paste', 'M5 3h6v2H5zM4 4H3v10h10V4h-1', 'Ctrl+V')}
        {item('all', 'Select all', null, 'Ctrl+A')}
        {sep('s1')}
        {item('grid', gridOn ? 'Turn off snap grid' : 'Turn on snap grid', null)}
        {item('rulers', rulersOn ? 'Hide rulers' : 'Show rulers', null)}
      </> : <>
        {count > 1 && <div style={{ padding: '6px 10px 4px', fontSize: 11, fontWeight: 700, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>{count} selected</div>}
        {item('copy', 'Copy', 'M5 5h8v8H5zM3 11V3h8', 'Ctrl+C')}
        {item('paste', 'Paste', 'M5 3h6v2H5zM4 4H3v10h10V4h-1', 'Ctrl+V')}
        {item('dup', 'Duplicate', CERT_ICONS.dup, 'Ctrl+D')}
        {item('copystyle', 'Copy style', 'M3 3h7v4H3zM10 5h2v4H7v4', 'Ctrl+Alt+C')}
        {item('pastestyle', 'Paste style', 'M3 3h7v4H3zM10 5h2v4H7v4', 'Ctrl+Alt+V')}
        {count > 1 && !grouped && item('group', 'Group', 'M2.5 2.5h11v11h-11zM5 5h3v3H5zM8 8h3v3H8z', 'Ctrl+G')}
        {grouped && item('ungroup', 'Ungroup', 'M3 3h5v5H3zM8 8h5v5H8z', 'Ctrl+Shift+G')}
        {item('del', 'Delete', CERT_ICONS.del, 'Del', true)}
        {sep('s1')}
        {item('front', 'Bring to front', CERT_ICONS.front)}
        {item('forward', 'Bring forward', CERT_ICONS.up)}
        {item('backward', 'Send backward', CERT_ICONS.down)}
        {item('back', 'Send to back', CERT_ICONS.back)}
        {sep('s2')}
        <div style={{ padding: '4px 10px 2px', fontSize: 11, fontWeight: 700, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>{count > 1 ? 'Align together' : 'Align on page'}</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6,1fr)', gap: 2, padding: '2px 6px 4px' }}>
          {[['left', 'aLeft'], ['hcenter', 'aHc'], ['right', 'aRight'], ['top', 'aTop'], ['vmiddle', 'aVm'], ['bottom', 'aBot']].map((a) => <button key={a[0]} type="button" className="ce-ctx-item" onClick={() => act('al-' + a[0])} style={{ height: 30, border: 'none', borderRadius: 6, background: 'transparent', cursor: 'pointer', color: 'var(--navy-900)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><CertIcon d={CERT_ICONS[a[1]]} /></button>)}
        </div>
        {sep('s3')}
        {item(locked ? 'unlock' : 'lock', locked ? 'Unlock' : 'Lock', locked ? CERT_ICONS.unlock : CERT_ICONS.lock)}
        {item('hide', 'Hide', CERT_ICONS.hide)}
      </>}
    </div>, document.body);
}

const CERT_HANDLES = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'];
const certHandlePos = { nw: [0, 0], n: [0.5, 0], ne: [1, 0], e: [1, 0.5], se: [1, 1], s: [0.5, 1], sw: [0, 1], w: [0, 0.5] };
const certHandleCursor = { nw: 'nwse-resize', se: 'nwse-resize', ne: 'nesw-resize', sw: 'nesw-resize', n: 'ns-resize', s: 'ns-resize', e: 'ew-resize', w: 'ew-resize' };

function CertEditor({ initialDesign, initialName, initialDescription, isNew, versionLabel, onClose, onSave, draftKey }) {
  const [design, setDesign] = React.useState(() => CE.clone(initialDesign));
  const [name, setName] = React.useState(initialName || '');
  const [description, setDescription] = React.useState(initialDescription || '');
  const [selIds, setSelIds] = React.useState([]);
  const selId = selIds.length === 1 ? selIds[0] : null;
  const setSelId = (id) => setSelIds(id ? [id] : []);
  const multi = selIds.length > 1;
  const selIdsRef = React.useRef(selIds); selIdsRef.current = selIds;
  const [grid, setGrid] = React.useState({ on: false, mm: 5 });
  const gridRef = React.useRef(grid); gridRef.current = grid;
  const [showRulers, setShowRulers] = React.useState(false);
  const [showSafe, setShowSafe] = React.useState(true);
  const [marquee, setMarquee] = React.useState(null);
  const [ctxMenu, setCtxMenu] = React.useState(null);
  const [palSearch, setPalSearch] = React.useState('');
  const [libOpen, setLibOpen] = React.useState(false);
  const [libItems, setLibItems] = React.useState(() => CE.loadLibrary());
  React.useEffect(() => {
    if (!libOpen) return;
    const down = (e) => { if (e.target.closest && (e.target.closest('[data-ce-portal]') || e.target.closest('.ce-pal'))) return; setLibOpen(false); };
    const key = (e) => { if (e.key === 'Escape') setLibOpen(false); };
    document.addEventListener('mousedown', down); document.addEventListener('keydown', key);
    return () => { document.removeEventListener('mousedown', down); document.removeEventListener('keydown', key); };
  }, [libOpen]);
  const [cropFor, setCropFor] = React.useState(null);
  const [helpOpen, setHelpOpen] = React.useState(false);
  const [rescaleOn, setRescaleOn] = React.useState(true);
  const [sigPad, setSigPad] = React.useState(null);
  const [libQ, setLibQ] = React.useState('');
  const [libKind, setLibKind] = React.useState('all');
  const [bgBusy, setBgBusy] = React.useState(false);
  const [zoom, setZoom] = React.useState(0.8);
  const [past, setPast] = React.useState([]);
  const [future, setFuture] = React.useState([]);
  const [dirty, setDirty] = React.useState(!!isNew);
  const [guides, setGuides] = React.useState([]);
  const [tab, setTab] = React.useState('props');
  const [toast, setToast] = React.useState(null);
  const [busy, setBusy] = React.useState('');
  const [previewData, setPreviewData] = React.useState(null);
  const [previewLabel, setPreviewLabel] = React.useState('Sample data');
  const [previewOpen, setPreviewOpen] = React.useState(false);
  const [mainEvents, setMainEvents] = React.useState(null);
  const [pvSub, setPvSub] = React.useState('');
  const [pvAtts, setPvAtts] = React.useState(null);
  const [tick, force] = React.useReducer((x) => x + 1, 0);
  const leaving = React.useContext(CertLeaveCtx);
  const [palGhost, setPalGhost] = React.useState(null);
  const [layerDrag, setLayerDrag] = React.useState(null);
  const pendingPos = React.useRef(null);
  const suppressPalClick = React.useRef(false);
  const layerRows = React.useRef({});

  const designRef = React.useRef(design); designRef.current = design;
  const zoomRef = React.useRef(zoom); zoomRef.current = zoom;
  const canvasRef = React.useRef(null);
  const stageRef = React.useRef(null);
  const dragRef = React.useRef(null);
  const lastCommit = React.useRef({ key: null, t: 0 });
  const textRef = React.useRef(null);
  const imgInput = React.useRef(null);
  const imgTarget = React.useRef(null);
  const bgImgInput = React.useRef(null);
  const bgPdfInput = React.useRef(null);

  const W = design.page.w, H = design.page.h;
  const sel = design.elements.find((e) => e.id === selId) || null;
  const layoutLocked = !!(design.settings && design.settings.layoutLocked);
  const layoutLockedRef = React.useRef(layoutLocked); layoutLockedRef.current = layoutLocked;
  React.useEffect(() => {
    if (!dirty || !draftKey) return;
    const t = setTimeout(() => CE.saveDraft(draftKey, { design: designRef.current, name, description }), 1000);
    return () => clearTimeout(t);
  }, [design, name, description, dirty, draftKey]);

  function flash(msg, isError) { setToast({ msg, isError }); setTimeout(() => setToast(null), isError ? 4500 : 2200); }

  function commit(next, key) {
    const now = Date.now();
    const coalesce = key && lastCommit.current.key === key && now - lastCommit.current.t < 900;
    lastCommit.current = { key, t: now };
    const prevDesign = designRef.current;
    if (!coalesce) { setPast((p) => p.slice(-59).concat([prevDesign])); setFuture([]); }
    designRef.current = next; setDesign(next); setDirty(true);
  }
  function updateEl(id, patch, key) {
    const d = designRef.current;
    commit({ ...d, elements: d.elements.map((e) => (e.id === id ? { ...e, ...patch } : e)) }, key ? key + ':' + id : null);
  }
  function setPage(patch) { const d = designRef.current; commit({ ...d, page: { ...d.page, ...patch } }); }
  function setBg(patch, key) { const d = designRef.current; commit({ ...d, background: { ...d.background, ...patch } }, key); }
  function undo() { if (!past.length) return; const prev = past[past.length - 1]; setPast(past.slice(0, -1)); setFuture([designRef.current].concat(future)); designRef.current = prev; setDesign(prev); setDirty(true); lastCommit.current = { key: null, t: 0 }; }
  function redo() { if (!future.length) return; const next = future[0]; setFuture(future.slice(1)); setPast(past.concat([designRef.current])); designRef.current = next; setDesign(next); setDirty(true); lastCommit.current = { key: null, t: 0 }; }

  function addEl(el) {
    const d = designRef.current;
    const placed = { ...el, x: el.x != null ? el.x : (d.page.w - el.w) / 2, y: el.y != null ? el.y : (d.page.h - el.h) / 2 };
    commit({ ...d, elements: d.elements.concat([placed]) });
    setSelId(placed.id); setTab('props');
  }
  function removeSel() { const ids = selIdsRef.current; if (!ids.length) return; const d = designRef.current; commit({ ...d, elements: d.elements.filter((e) => ids.indexOf(e.id) === -1) }); setSelIds([]); }
  function duplicateSel() {
    const ids = selIdsRef.current; if (!ids.length) return; const d = designRef.current;
    const copies = d.elements.filter((e) => ids.indexOf(e.id) !== -1).map((e) => ({ ...CE.clone(e), id: CE.uid(), name: (e.name || e.type) + ' copy', x: e.x + 12, y: e.y + 12, locked: false }));
    commit({ ...d, elements: d.elements.concat(copies) }); setSelIds(copies.map((c) => c.id));
  }
  const STYLE_KEYS = ['fontFamily', 'fontSize', 'color', 'bold', 'italic', 'underline', 'align', 'letterSpacing', 'lineHeight', 'shadow', 'outline', 'fill', 'stroke', 'strokeWidth', 'radius', 'thickness', 'dashed', 'lineStyle', 'style', 'opacity', 'fit'];
  function copySel() { const ids = selIdsRef.current; if (!ids.length) return; const els = designRef.current.elements.filter((e) => ids.indexOf(e.id) !== -1); CE.setClip({ els: CE.clone(els), at: Date.now() }); flash('Copied ' + els.length + ' element' + (els.length === 1 ? '' : 's')); }
  function pasteClip() {
    if (layoutLockedRef.current) return;
    const clip = CE.getClip(); if (!clip || !clip.els || !clip.els.length) { flash('Nothing copied yet.', true); return; }
    const d = designRef.current, here = clip.els.some((e) => d.elements.some((x) => x.id === e.id));
    const gmap = {};
    const els = clip.els.map((e) => { const n = { ...CE.clone(e), id: CE.uid(), locked: false }; if (here) { n.x += 14; n.y += 14; } if (e.group) n.group = gmap[e.group] || (gmap[e.group] = CE.uid('g')); return n; });
    addMany(els); flash('Pasted ' + els.length + ' element' + (els.length === 1 ? '' : 's'));
  }
  function copyStyle() { const el = designRef.current.elements.find((e) => e.id === selIdsRef.current[0]); if (!el) return; const st = {}; STYLE_KEYS.forEach((k) => { if (el[k] !== undefined) st[k] = CE.clone(el[k]); }); CE.setStyleClip({ type: el.type, style: st }); flash('Style copied'); }
  function pasteStyle() {
    const sc = CE.getStyleClip(); if (!sc) { flash('Copy a style first.', true); return; }
    const isTextT = (t) => t === 'text' || t === 'field', ids = selIdsRef.current, d = designRef.current;
    commit({ ...d, elements: d.elements.map((e) => {
      if (ids.indexOf(e.id) === -1) return e;
      const n = { ...e }; Object.keys(sc.style).forEach((k) => { const textOnly = ['fontFamily', 'fontSize', 'bold', 'italic', 'underline', 'align', 'letterSpacing', 'lineHeight', 'shadow', 'outline'].indexOf(k) !== -1; if (textOnly && !isTextT(e.type)) return; if (k === 'style' && e.type !== 'frame') return; if ((k === 'fill' || k === 'stroke' || k === 'strokeWidth') && e.type !== 'shape') return; if ((k === 'thickness' || k === 'dashed' || k === 'lineStyle') && e.type !== 'line' && e.type !== 'frame') return; if (k === 'color' && e.type === 'shape') return; n[k] = CE.clone(sc.style[k]); });
      return n;
    }) });
  }
  function groupSel() { const ids = selIdsRef.current; if (ids.length < 2) return; patchSel({ group: CE.uid('g') }); flash('Grouped ' + ids.length + ' elements'); }
  function ungroupSel() { patchSel({ group: null }); flash('Ungrouped'); }
  function changePage(patch) {
    const d = designRef.current, nw = patch.w != null ? patch.w : d.page.w, nh = patch.h != null ? patch.h : d.page.h;
    const resized = rescaleOn && (Math.abs(nw - d.page.w) > 0.5 || Math.abs(nh - d.page.h) > 0.5);
    commit({ ...d, page: { ...d.page, ...patch }, elements: resized ? CE.rescaleElements(d.elements, d.page.w, d.page.h, nw, nh) : d.elements });
    if (resized) flash('Design resized to fit. Check the layout, or press Undo.');
  }
  async function toggleLayoutLock() {
    const d = designRef.current, on = !(d.settings && d.settings.layoutLocked);
    if (!on && !(await window.udConfirm('Unlock the layout? Everyone editing this template will be able to move, resize and delete things again.'))) return;
    commit({ ...d, settings: { ...(d.settings || {}), layoutLocked: on } });
    if (on) { setSelIds([]); flash('Layout locked. Only wording and details can be changed now.'); }
  }
  async function testPrint() { setBusy('Preparing test print…'); try { CE.printBlob(await CE.buildTestPdf(designRef.current, previewData)); } catch (e) { flash(e.message || 'Could not prepare the test print.', true); } setBusy(''); }
  function patchSel(patch) { const ids = selIdsRef.current, d = designRef.current; commit({ ...d, elements: d.elements.map((e) => (ids.indexOf(e.id) !== -1 ? { ...e, ...patch } : e)) }); }
  function addMany(els) { const d = designRef.current; commit({ ...d, elements: d.elements.concat(els) }); setSelIds(els.map((e) => e.id)); setTab('props'); }
  function reorderSel(kind) {
    const d = designRef.current, ids = selIdsRef.current; if (!ids.length) return;
    const isS = (e) => ids.indexOf(e.id) !== -1; let arr = d.elements.slice();
    if (kind === 'front') arr = arr.filter((e) => !isS(e)).concat(arr.filter(isS));
    else if (kind === 'back') arr = arr.filter(isS).concat(arr.filter((e) => !isS(e)));
    else if (kind === 'forward') { for (let i = arr.length - 2; i >= 0; i--) if (isS(arr[i]) && !isS(arr[i + 1])) { const t = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = t; } }
    else { for (let i = 1; i < arr.length; i++) if (isS(arr[i]) && !isS(arr[i - 1])) { const t = arr[i]; arr[i] = arr[i - 1]; arr[i - 1] = t; } }
    commit({ ...d, elements: arr });
  }
  function selBox(els) { const x0 = Math.min.apply(null, els.map((e) => e.x)), y0 = Math.min.apply(null, els.map((e) => e.y)); return { x: x0, y: y0, w: Math.max.apply(null, els.map((e) => e.x + e.w)) - x0, h: Math.max.apply(null, els.map((e) => e.y + e.h)) - y0 }; }
  function alignSel(how) {
    const d = designRef.current, ids = selIdsRef.current, els = d.elements.filter((e) => ids.indexOf(e.id) !== -1 && !e.locked); if (!els.length) return;
    const b = ids.length > 1 ? selBox(d.elements.filter((e) => ids.indexOf(e.id) !== -1)) : { x: 0, y: 0, w: d.page.w, h: d.page.h };
    const pos = (e) => ({ left: { x: b.x }, hcenter: { x: b.x + (b.w - e.w) / 2 }, right: { x: b.x + b.w - e.w }, top: { y: b.y }, vmiddle: { y: b.y + (b.h - e.h) / 2 }, bottom: { y: b.y + b.h - e.h } }[how]);
    commit({ ...d, elements: d.elements.map((e) => (els.indexOf(e) !== -1 ? { ...e, ...pos(e) } : e)) });
  }
  function distributeSel(axis) {
    const d = designRef.current, ids = selIdsRef.current, els = d.elements.filter((e) => ids.indexOf(e.id) !== -1 && !e.locked); if (els.length < 3) return;
    const P = axis === 'h' ? 'x' : 'y', S = axis === 'h' ? 'w' : 'h';
    const sorted = els.slice().sort((a, b) => a[P] - b[P]);
    const first = sorted[0], last = sorted[sorted.length - 1], span = last[P] + last[S] - first[P], total = sorted.reduce((t, e) => t + e[S], 0), gap = (span - total) / (sorted.length - 1);
    const np = {}; let cur = first[P]; sorted.forEach((e) => { np[e.id] = cur; cur += e[S] + gap; });
    commit({ ...d, elements: d.elements.map((e) => (np[e.id] != null ? { ...e, [P]: Math.round(np[e.id] * 2) / 2 } : e)) });
  }
  function moveLayer(id, dir) {
    const d = designRef.current, arr = d.elements.slice(), i = arr.findIndex((e) => e.id === id), j = i + dir;
    if (j < 0 || j >= arr.length) return; const t = arr[i]; arr[i] = arr[j]; arr[j] = t; commit({ ...d, elements: arr });
  }

  // fit + fonts
  function fit() {
    const st = stageRef.current; if (!st) return;
    const z = Math.min((st.clientWidth - 64) / designRef.current.page.w, (st.clientHeight - 64) / designRef.current.page.h);
    setZoom(Math.max(0.2, Math.min(2, Math.round(z * 100) / 100)));
  }
  React.useEffect(() => { fit(); const ro = new ResizeObserver(() => {}); return () => ro.disconnect(); }, []);
  React.useEffect(() => { fit(); }, [W, H]);
  const fontKey = design.elements.filter((e) => e.type === 'text' || e.type === 'field').map((e) => e.fontFamily + (e.bold ? 'b' : '') + (e.italic ? 'i' : '')).join('|');
  React.useEffect(() => { CE.preload(designRef.current).then(force); }, [fontKey]);

  // render
  React.useEffect(() => {
    const c = canvasRef.current; if (!c) return;
    const dpr = window.devicePixelRatio || 1, s = zoom * dpr;
    c.width = Math.round(W * s); c.height = Math.round(H * s);
    const ctx = c.getContext('2d'); ctx.setTransform(s, 0, 0, s, 0, 0);
    CE.render(ctx, design, previewData, force);
  }, [design, zoom, previewData, tick]);

  // dragging
  function startDrag(e, id, mode, handle) {
    if (e.button === 2) return;
    e.stopPropagation(); e.preventDefault();
    setCtxMenu(null);
    const all = designRef.current.elements, el = all.find((x) => x.id === id);
    if (!el) return;
    const groupIds = el.group && !e.altKey ? all.filter((x) => x.group === el.group && !x.hidden).map((x) => x.id) : [id];
    if (e.shiftKey && mode === 'move') { setSelIds((cur) => (cur.indexOf(id) !== -1 ? cur.filter((x) => groupIds.indexOf(x) === -1) : cur.concat(groupIds.filter((g) => cur.indexOf(g) === -1)))); return; }
    if (layoutLockedRef.current) { setSelIds([id]); setTab('props'); return; }
    let cur = selIdsRef.current;
    if (groupIds.length > 1 && cur.indexOf(id) === -1) { cur = groupIds; setSelIds(groupIds); }
    const inGroup = mode === 'move' && cur.indexOf(id) !== -1 && cur.length > 1;
    if (!inGroup && !(groupIds.length > 1 && mode === 'move')) setSelIds([id]);
    const group = inGroup ? cur : [id];
    const movers = group.map((g) => all.find((x) => x.id === g)).filter((x) => x && !x.locked);
    if (!movers.length || (mode === 'resize' && el.locked)) return;
    const origs = {}; movers.forEach((m) => { origs[m.id] = { x: m.x, y: m.y, w: m.w, h: m.h }; });
    dragRef.current = { id, mode, handle, sx: e.clientX, sy: e.clientY, orig: { ...el }, origs, start: designRef.current, moved: false };
    window.addEventListener('pointermove', onMove);
    window.addEventListener('pointerup', onUp);
  }
  function startGroupResize(e, handle) {
    e.stopPropagation(); e.preventDefault(); if (layoutLockedRef.current) return;
    const all = designRef.current.elements, ids = selIdsRef.current, els = all.filter((x) => ids.indexOf(x.id) !== -1 && !x.locked);
    if (els.length < 2) return;
    const origs = {}; els.forEach((m) => { origs[m.id] = { x: m.x, y: m.y, w: m.w, h: m.h, fontSize: m.fontSize, letterSpacing: m.letterSpacing }; });
    dragRef.current = { mode: 'gresize', handle, sx: e.clientX, sy: e.clientY, box: selBox(els), origs, start: designRef.current, moved: false };
    window.addEventListener('pointermove', onMove); window.addEventListener('pointerup', onUp);
  }
  function startRotate(e, id) {
    e.stopPropagation(); e.preventDefault(); if (layoutLockedRef.current) return;
    const el = designRef.current.elements.find((x) => x.id === id); if (!el || el.locked) return;
    const r = canvasRef.current.getBoundingClientRect(), z = zoomRef.current;
    dragRef.current = { mode: 'rotate', id, cx: r.left + (el.x + el.w / 2) * z, cy: r.top + (el.y + el.h / 2) * z, start: designRef.current, moved: false };
    window.addEventListener('pointermove', onMove); window.addEventListener('pointerup', onUp);
  }
  function snapGuides(n, exclude, z) {
    const pg = designRef.current.page, g = [], thr = 6 / z, others = designRef.current.elements.filter((x) => !exclude[x.id] && !x.hidden);
    const tx = [0, pg.w / 2, pg.w], ty = [0, pg.h / 2, pg.h];
    others.forEach((x) => { tx.push(x.x, x.x + x.w / 2, x.x + x.w); ty.push(x.y, x.y + x.h / 2, x.y + x.h); });
    let bx = null; [0, n.w / 2, n.w].forEach((off) => tx.forEach((t) => { const diff = t - (n.x + off); if (Math.abs(diff) < thr && (!bx || Math.abs(diff) < Math.abs(bx.diff))) bx = { diff, t }; }));
    let by = null; [0, n.h / 2, n.h].forEach((off) => ty.forEach((t) => { const diff = t - (n.y + off); if (Math.abs(diff) < thr && (!by || Math.abs(diff) < Math.abs(by.diff))) by = { diff, t }; }));
    if (bx) { n.x += bx.diff; g.push({ v: true, pos: bx.t, center: Math.abs(bx.t - pg.w / 2) < 0.01 }); }
    if (by) { n.y += by.diff; g.push({ v: false, pos: by.t, center: Math.abs(by.t - pg.h / 2) < 0.01 }); }
    // gaps to nearest neighbours + equal spacing
    const rowMates = others.filter((x) => x.y < n.y + n.h && x.y + x.h > n.y && x.w < pg.w * 0.85);
    const colMates = others.filter((x) => x.x < n.x + n.w && x.x + x.w > n.x && x.h < pg.h * 0.85);
    let L = null, R = null, T = null, B = null;
    rowMates.forEach((x) => { if (x.x + x.w <= n.x + 0.5 && (!L || x.x + x.w > L.x + L.w)) L = x; if (x.x >= n.x + n.w - 0.5 && (!R || x.x < R.x)) R = x; });
    colMates.forEach((x) => { if (x.y + x.h <= n.y + 0.5 && (!T || x.y + x.h > T.y + T.h)) T = x; if (x.y >= n.y + n.h - 0.5 && (!B || x.y < B.y)) B = x; });
    if (L && R && !bx) { const gl = n.x - (L.x + L.w), gr = R.x - (n.x + n.w); if (Math.abs(gl - gr) < thr * 1.5) { n.x += (gr - gl) / 2; } }
    if (T && B && !by) { const gt = n.y - (T.y + T.h), gb = B.y - (n.y + n.h); if (Math.abs(gt - gb) < thr * 1.5) { n.y += (gb - gt) / 2; } }
    const cyM = n.y + n.h / 2, cxM = n.x + n.w / 2;
    const eqH = L && R && Math.abs((n.x - (L.x + L.w)) - (R.x - (n.x + n.w))) < 0.75, eqV = T && B && Math.abs((n.y - (T.y + T.h)) - (B.y - (n.y + n.h))) < 0.75;
    if (L) g.push({ gap: true, axis: 'h', a: L.x + L.w, b: n.x, at: cyM, eq: eqH });
    if (R) g.push({ gap: true, axis: 'h', a: n.x + n.w, b: R.x, at: cyM, eq: eqH });
    if (T) g.push({ gap: true, axis: 'v', a: T.y + T.h, b: n.y, at: cxM, eq: eqV });
    if (B) g.push({ gap: true, axis: 'v', a: n.y + n.h, b: B.y, at: cxM, eq: eqV });
    return g;
  }
  function onMove(e) {
    const d = dragRef.current; if (!d) return;
    const z = zoomRef.current, dx = (e.clientX - d.sx) / z, dy = (e.clientY - d.sy) / z;
    if (!d.moved && Math.abs(dx) + Math.abs(dy) < 1.5) return;
    const gr = gridRef.current, gs = gr.mm * CE.MM, useGrid = gr.on && !e.altKey;
    let g = [];
    if (d.mode === 'rotate') {
      let ang = Math.atan2(e.clientY - d.cy, e.clientX - d.cx) * 180 / Math.PI + 90;
      if (e.shiftKey) ang = Math.round(ang / 15) * 15; else { const near = Math.round(ang / 90) * 90; if (Math.abs(ang - near) < 4) ang = near; }
      ang = ((Math.round(ang) % 360) + 360) % 360; if (ang > 180) ang -= 360;
      d.moved = true; const cur = designRef.current, next = { ...cur, elements: cur.elements.map((x) => (x.id === d.id ? { ...x, rotation: ang } : x)) };
      designRef.current = next; setDesign(next); return;
    }
    if (d.mode === 'gresize') {
      const b = d.box, h = d.handle, MIN = 12, nb = { x: b.x, y: b.y, w: b.w, h: b.h };
      if (h.indexOf('e') !== -1) nb.w = Math.max(MIN, b.w + dx);
      if (h.indexOf('s') !== -1) nb.h = Math.max(MIN, b.h + dy);
      if (h.indexOf('w') !== -1) { nb.w = Math.max(MIN, b.w - dx); nb.x = b.x + b.w - nb.w; }
      if (h.indexOf('n') !== -1) { nb.h = Math.max(MIN, b.h - dy); nb.y = b.y + b.h - nb.h; }
      if (h.length === 2 || e.shiftKey) { const r = b.w / b.h; if (nb.w / nb.h > r) nb.w = nb.h * r; else nb.h = nb.w / r; if (h.indexOf('w') !== -1) nb.x = b.x + b.w - nb.w; if (h.indexOf('n') !== -1) nb.y = b.y + b.h - nb.h; }
      const sx = nb.w / b.w, sy = nb.h / b.h, sc = Math.min(sx, sy);
      d.moved = true;
      const cur = designRef.current, next = { ...cur, elements: cur.elements.map((x) => {
        const o = d.origs[x.id]; if (!o) return x;
        const n = { ...x, x: Math.round((nb.x + (o.x - b.x) * sx) * 2) / 2, y: Math.round((nb.y + (o.y - b.y) * sy) * 2) / 2, w: Math.max(4, Math.round(o.w * sx * 2) / 2), h: Math.max(4, Math.round(o.h * sy * 2) / 2) };
        if (o.fontSize) n.fontSize = Math.max(4, Math.round(o.fontSize * sc * 2) / 2);
        if (o.letterSpacing) n.letterSpacing = o.letterSpacing * sc;
        return n;
      }) };
      designRef.current = next; setDesign(next); setGuides([]); return;
    }
    if (d.mode === 'move') {
      const ids = Object.keys(d.origs);
      const b = selBox(ids.map((k) => d.origs[k]));
      const n = { x: b.x + dx, y: b.y + dy, w: b.w, h: b.h };
      if (useGrid) { n.x = Math.round(n.x / gs) * gs; n.y = Math.round(n.y / gs) * gs; }
      else if (!e.altKey) g = snapGuides(n, d.origs, z);
      const ddx = n.x - b.x, ddy = n.y - b.y;
      d.moved = true;
      const cur = designRef.current, next = { ...cur, elements: cur.elements.map((x) => (d.origs[x.id] ? { ...x, x: Math.round((d.origs[x.id].x + ddx) * 2) / 2, y: Math.round((d.origs[x.id].y + ddy) * 2) / 2 } : x)) };
      designRef.current = next; setDesign(next); setGuides(g);
      return;
    }
    const o = d.orig, n = { x: o.x, y: o.y, w: o.w, h: o.h }, h = d.handle, MIN = 6;
    if (h.indexOf('e') !== -1) n.w = Math.max(MIN, o.w + dx);
    if (h.indexOf('s') !== -1) n.h = Math.max(MIN, o.h + dy);
    if (h.indexOf('w') !== -1) { n.w = Math.max(MIN, o.w - dx); n.x = o.x + o.w - n.w; }
    if (h.indexOf('n') !== -1) { n.h = Math.max(MIN, o.h - dy); n.y = o.y + o.h - n.h; }
    if (e.shiftKey && h.length === 2) { const r = o.w / o.h; if (n.w / n.h > r) n.w = n.h * r; else n.h = n.w / r; if (h.indexOf('w') !== -1) n.x = o.x + o.w - n.w; if (h.indexOf('n') !== -1) n.y = o.y + o.h - n.h; }
    else if (useGrid) {
      if (h.indexOf('e') !== -1) n.w = Math.max(MIN, Math.round((n.x + n.w) / gs) * gs - n.x);
      if (h.indexOf('s') !== -1) n.h = Math.max(MIN, Math.round((n.y + n.h) / gs) * gs - n.y);
      if (h.indexOf('w') !== -1) { const r = o.x + o.w, nx = Math.min(r - MIN, Math.round(n.x / gs) * gs); n.x = nx; n.w = r - nx; }
      if (h.indexOf('n') !== -1) { const bt = o.y + o.h, ny = Math.min(bt - MIN, Math.round(n.y / gs) * gs); n.y = ny; n.h = bt - ny; }
    }
    ['x', 'y', 'w', 'h'].forEach((k) => { n[k] = Math.round(n[k] * 2) / 2; });
    d.moved = true;
    const cur = designRef.current, next = { ...cur, elements: cur.elements.map((x) => (x.id === d.id ? { ...x, ...n } : x)) };
    designRef.current = next; setDesign(next); setGuides(g);
  }
  function stageDown(e) {
    if (e.button !== 0) return;
    setCtxMenu(null);
    if (layoutLockedRef.current) { setSelIds([]); return; }
    const c = canvasRef.current; if (!c) return;
    const r = c.getBoundingClientRect(), z = zoomRef.current, add = e.shiftKey;
    const sx = (e.clientX - r.left) / z, sy = (e.clientY - r.top) / z; let moved = false;
    const move = (ev) => {
      const x = (ev.clientX - r.left) / z, y = (ev.clientY - r.top) / z;
      if (!moved && Math.abs(x - sx) * z + Math.abs(y - sy) * z < 4) return;
      moved = true; document.body.style.userSelect = 'none';
      setMarquee({ x: Math.min(sx, x), y: Math.min(sy, y), w: Math.abs(x - sx), h: Math.abs(y - sy) });
    };
    const up = (ev) => {
      window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', up);
      document.body.style.userSelect = '';
      if (!moved) { if (!add) setSelIds([]); return; }
      const x = (ev.clientX - r.left) / z, y = (ev.clientY - r.top) / z, m = { x: Math.min(sx, x), y: Math.min(sy, y), w: Math.abs(x - sx), h: Math.abs(y - sy) };
      setMarquee(null);
      const hits = designRef.current.elements.filter((el) => !el.hidden && !el.locked && el.x >= m.x - 1 && el.y >= m.y - 1 && el.x + el.w <= m.x + m.w + 1 && el.y + el.h <= m.y + m.h + 1).map((el) => el.id);
      setSelIds((cur) => (add ? cur.concat(hits.filter((h) => cur.indexOf(h) === -1)) : hits));
      if (hits.length) setTab('props');
    };
    window.addEventListener('pointermove', move); window.addEventListener('pointerup', up);
  }
  function onUp() {
    const d = dragRef.current; dragRef.current = null;
    window.removeEventListener('pointermove', onMove); window.removeEventListener('pointerup', onUp);
    setGuides([]);
    if (d && d.moved) { setPast((p) => p.slice(-59).concat([d.start])); setFuture([]); setDirty(true); lastCommit.current = { key: null, t: 0 }; }
  }

  // keyboard
  React.useEffect(() => {
    function onKey(e) {
      const t = e.target, typing = t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT' || t.isContentEditable);
      const mod = e.metaKey || e.ctrlKey;
      if (mod && e.key.toLowerCase() === 's') { e.preventDefault(); save(); return; }
      if (typing) return;
      if (mod && e.key.toLowerCase() === 'z') { e.preventDefault(); if (e.shiftKey) redo(); else undo(); return; }
      if (mod && e.key.toLowerCase() === 'y') { e.preventDefault(); redo(); return; }
      if (mod && e.key.toLowerCase() === 'd') { e.preventDefault(); if (!layoutLockedRef.current) duplicateSel(); return; }
      if (e.key === '?' || (e.shiftKey && e.key === '/')) { e.preventDefault(); setHelpOpen((v) => !v); return; }
      if (mod && !e.altKey && e.key.toLowerCase() === 'c') { if (selIdsRef.current.length) { e.preventDefault(); copySel(); } return; }
      if (mod && e.altKey && e.key.toLowerCase() === 'c') { e.preventDefault(); copyStyle(); return; }
      if (mod && e.altKey && e.key.toLowerCase() === 'v') { e.preventDefault(); if (!layoutLockedRef.current) pasteStyle(); return; }
      if (mod && e.key.toLowerCase() === 'v') { e.preventDefault(); pasteClip(); return; }
      if (layoutLockedRef.current) { if (e.key === 'Escape') setSelIds([]); return; }
      if (mod && e.key.toLowerCase() === 'g') { e.preventDefault(); if (e.shiftKey) ungroupSel(); else groupSel(); return; }
      if (mod && e.key.toLowerCase() === 'a') { e.preventDefault(); setSelIds(designRef.current.elements.filter((x) => !x.hidden && !x.locked).map((x) => x.id)); setTab('props'); return; }
      if (e.key === 'Escape') { if (ctxMenu) setCtxMenu(null); else setSelIds([]); return; }
      const ids = selIdsRef.current; if (!ids.length) return;
      if (e.key === 'Delete' || e.key === 'Backspace') { e.preventDefault(); removeSel(); return; }
      const step = e.shiftKey ? 10 : 1, mv = { ArrowLeft: [-step, 0], ArrowRight: [step, 0], ArrowUp: [0, -step], ArrowDown: [0, step] }[e.key];
      if (mv) { e.preventDefault(); const d = designRef.current; commit({ ...d, elements: d.elements.map((x) => (ids.indexOf(x.id) !== -1 && !x.locked ? { ...x, x: x.x + mv[0], y: x.y + mv[1] } : x)) }, 'nudge:' + ids.join(',')); }
    }
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  });

  // uploads
  async function onImageFile(file) {
    if (!file) return;
    try {
      const raw = await CE.readFileAsDataUrl(file), small = await CE.downscaleImage(raw, 1600), id = CE.putAsset(small);
      CE.addToLibrary(id, imgTarget.current === 'signature' ? 'signature' : 'image', (file.name || 'Image').replace(/\.[a-z0-9]+$/i, '')); setLibItems(CE.loadLibrary());
      const img = new Image(); img.src = small; await img.decode().catch(() => {});
      const r = img.naturalWidth && img.naturalHeight ? img.naturalWidth / img.naturalHeight : 2;
      const target = imgTarget.current;
      if (target === 'replace' && sel) updateEl(sel.id, { src: id });
      else { const w = target === 'signature' ? 180 : 160, h = Math.round(w / r), pt = pendingPos.current; pendingPos.current = null; addEl({ id: CE.uid(), type: 'image', name: target === 'signature' ? 'Signature' : 'Image', src: id, fit: 'contain', w, h, opacity: 1, x: pt ? pt.x - w / 2 : null, y: pt ? pt.y - h / 2 : null }); }
    } catch (err) { flash(err.message || 'Could not add that image.', true); }
  }
  async function onBgImage(file) {
    if (!file) return;
    try { const raw = await CE.readFileAsDataUrl(file), small = await CE.downscaleImage(raw, 2200); setBg({ type: 'image', image: CE.putAsset(small) }); }
    catch (err) { flash(err.message || 'Could not use that image.', true); }
  }
  async function onBgPdf(file) {
    if (!file) return;
    setBusy('Reading PDF…');
    try {
      const r = await CE.pdfToBackground(file), id = CE.putAsset(r.dataUrl), d = designRef.current;
      commit({ ...d, page: { size: 'custom', orientation: r.w > r.h ? 'landscape' : 'portrait', w: r.w, h: r.h }, background: { type: 'pdf', image: id, fileName: file.name } });
      if (r.pages > 1) flash('Only the first page of the PDF is used.');
    } catch (err) { flash(err.message || 'Could not read that PDF.', true); }
    setBusy('');
  }

  // preview data
  async function openPreview() {
    setPreviewOpen((o) => !o);
    if (!mainEvents) { try { setMainEvents(await window.fetchMainEventsLive()); } catch (e) { setMainEvents([]); } }
  }
  const subOptions = (mainEvents || []).flatMap((m) => m.subEvents.map((s) => ({ m, s })));
  async function pickPreviewSub(id) {
    setPvSub(id); setPvAtts(null);
    if (!id) return;
    try { setPvAtts(await CE.fetchAttendees(id)); } catch (e) { setPvAtts([]); flash('Could not load attendees.', true); }
  }
  function pickPreviewAtt(ticketId) {
    const o = subOptions.find((x) => x.s.id === pvSub), att = (pvAtts || []).find((a) => a.ticketId === ticketId);
    setPreviewData(CE.buildData(o.m, o.s, att)); setPreviewLabel(att ? (att.first + ' ' + att.last) : o.s.title); setPreviewOpen(false);
  }

  async function exportPdf() {
    setBusy('Building PDF…');
    try { const blob = await CE.buildCombinedPdf(designRef.current, [previewData]); CE.download(blob, CE.safeName(name || 'certificate') + '.pdf'); }
    catch (err) { flash(err.message || 'Export failed.', true); }
    setBusy('');
  }
  async function save(note) {
    if (!name.trim()) { flash('Give the template a name first.', true); return; }
    setBusy('Saving…');
    try { const n = await onSave({ name: name.trim(), description, note: typeof note === 'string' ? note : '' }, designRef.current); setDirty(false); if (draftKey) CE.clearDraft(draftKey); CE.clearDraft('new'); flash('Saved as version ' + n); }
    catch (err) { flash(err.message || 'Could not save.', true); }
    setBusy('');
  }
  function insertToken(k) {
    if (!sel || sel.type !== 'text') return;
    const ta = textRef.current, tok = '{' + k + '}', txt = sel.text || '';
    const a = ta && document.activeElement === ta ? ta.selectionStart : txt.length;
    const b = ta && document.activeElement === ta ? ta.selectionEnd : txt.length;
    const pre = txt.slice(0, a), post = txt.slice(b);
    const sp1 = pre && !/\s$/.test(pre) ? ' ' : '', sp2 = post && !/^\s/.test(post) ? ' ' : '';
    const next = pre + sp1 + tok + sp2 + post;
    updateEl(sel.id, { text: next });
    const caret = (pre + sp1 + tok).length;
    setTimeout(() => { if (textRef.current) { textRef.current.focus(); textRef.current.setSelectionRange(caret, caret); } }, 20);
  }
  async function close() { if (dirty && !(await window.udConfirm({ title: 'Leave without saving?', message: 'Your latest changes haven\'t been saved as a version yet.', okLabel: 'Leave without saving', cancelLabel: 'Keep editing' }))) return; if (draftKey) CE.clearDraft(draftKey); onClose(); }

  // ---------- panels ----------
  const SAFE = CE.SAFE_MM * CE.MM;
  const unsafe = design.elements.filter((el) => {
    if (el.hidden || el.type === 'shape') return false;
    const ins = el.type === 'frame' ? (el.inset || 0) : 0, x0 = el.x + ins, y0 = el.y + ins, x1 = el.x + el.w - ins, y1 = el.y + el.h - ins;
    return x0 < SAFE - 0.5 || y0 < SAFE - 0.5 || x1 > W - SAFE + 0.5 || y1 > H - SAFE + 0.5;
  });
  const palGroups = [
    { group: 'Text', items: [
      { key: 'text', label: 'Text box', ico: 'text', make: () => CE.textEl({ x: null, y: null, text: 'Double-click to edit' }) },
      { key: 't-head', label: 'Heading', ico: 't-head', make: () => CE.textEl({ x: null, y: null, name: 'Heading', text: 'Certificate of Completion', w: 520, h: 52, fontFamily: 'Playfair Display', fontSize: 38, bold: true, color: CE.BRAND.navy }) },
      { key: 't-sub', label: 'Subheading', ico: 't-sub', make: () => CE.textEl({ x: null, y: null, name: 'Subheading', text: 'PROUDLY PRESENTED TO', w: 400, h: 20, fontSize: 11, bold: true, letterSpacing: 4, color: CE.BRAND.orangeDeep }) },
      { key: 't-para', label: 'Paragraph', ico: 't-para', make: () => CE.textEl({ x: null, y: null, name: 'Paragraph', text: 'has successfully completed {sub_event_title}, held on {event_date}.', w: 480, h: 50, fontSize: 14, color: '#444444', lineHeight: 1.45 }) },
      { key: 't-quote', label: 'Quote line', ico: 't-quote', make: () => CE.textEl({ x: null, y: null, name: 'Quote', text: '“Strength in every movement.”', w: 420, h: 30, fontFamily: 'Cormorant Garamond', italic: true, fontSize: 20, color: CE.BRAND.navy }) },
      { key: 't-script', label: 'Script name style', ico: 't-script', make: () => CE.fieldEl('attendee_name', { x: null, y: null, w: 480, h: 70, fontFamily: 'Great Vibes', fontSize: 54, color: CE.BRAND.navy }) },
      { key: 't-small', label: 'Small print', ico: 't-small', make: () => CE.textEl({ x: null, y: null, name: 'Small print', text: 'Certificate no. {cert_number}', w: 260, h: 16, fontFamily: 'IBM Plex Mono', fontSize: 8, color: '#888888' }) },
    ] },
    { group: 'Auto-filled details', items: Object.keys(CE.FIELDS).map((k) => ({ key: 'f-' + k, label: CE.FIELDS[k].label, ico: 'field', make: () => CE.fieldEl(k, { x: null, y: null, w: k === 'attendee_name' ? 420 : 320, h: k === 'attendee_name' ? 56 : 30, fontSize: k === 'attendee_name' ? 40 : 16 }) })) },
    { group: 'Ready-made blocks', items: [
      { key: 'b-sig', label: 'Signature block', ico: 'b-sig', block: 'signature' },
      { key: 'b-sig2', label: 'Two signatures', ico: 'b-sig2', block: 'signature2' },
      { key: 'b-seal', label: 'Seal / badge', ico: 'b-seal', block: 'seal' },
      { key: 'b-foot', label: 'Number + date footer', ico: 'b-foot', block: 'footer' },
      { key: 'b-title', label: 'Title + subtitle', ico: 'b-title', block: 'titleblock' },
      { key: 'b-dv', label: 'Date + venue line', ico: 'b-dv', block: 'datevenue' },
      { key: 'b-logo', label: 'Logo header', ico: 'b-logo', block: 'logohead' },
      { key: 'b-info', label: 'Awarded-for box', ico: 'b-info', block: 'qrbox' },
      { key: 'b-hours', label: 'Hours / credits circle', ico: 'b-hours', block: 'hours' },
      { key: 'b-person', label: 'Name + role + organization', ico: 'b-person', block: 'qrlabel' },
    ] },
    { group: 'Decorations', items: [
      { key: 'd-ribbon', label: 'Ribbon banner', ico: 'd-ribbon', block: 'ribbon' },
      { key: 'd-burst', label: 'Starburst seal', ico: 'd-burst', block: 'starburst' },
      { key: 'd-div', label: 'Diamond divider', ico: 'd-div', block: 'dotdivider' },
      { key: 'd-laurel', label: 'Laurel wreath', ico: 'd-laurel', block: 'laurel' },
      { key: 'd-stamp', label: 'Verified stamp', ico: 'd-stamp', block: 'stamp' },
      { key: 'd-shield', label: 'Shield', ico: 'd-shield', make: () => ({ id: CE.uid(), type: 'shape', name: 'Shield', shape: 'shield', fill: CE.BRAND.navy, stroke: '#B8892B', strokeWidth: 2, w: 90, h: 106, opacity: 1 }) },
      { key: 'd-check', label: 'Check badge', ico: 'd-check', make: () => ({ id: CE.uid(), type: 'shape', name: 'Check badge', shape: 'check', fill: '#1B7A4D', stroke: '#FFFFFF', strokeWidth: 0, w: 60, h: 60, opacity: 1 }) },
      { key: 'd-heart', label: 'Heart', ico: 'd-heart', make: () => ({ id: CE.uid(), type: 'shape', name: 'Heart', shape: 'heart', fill: '#C2334D', stroke: '#C2334D', strokeWidth: 0, w: 60, h: 54, opacity: 1 }) },
      { key: 'd-star', label: 'Star', ico: 'd-star', make: () => ({ id: CE.uid(), type: 'shape', name: 'Star', shape: 'star', fill: '#B8892B', stroke: '#B8892B', strokeWidth: 0, w: 60, h: 60, opacity: 1 }) },
      { key: 'd-corner', label: 'Corner ornament', ico: 'fr-corners', make: () => ({ id: CE.uid(), type: 'frame', name: 'Corner ornament', style: 'corners', color: CE.BRAND.orange, thickness: 2.5, inset: 0, w: 140, h: 100, opacity: 1 }) },
    ] },
    { group: 'Images', items: [
      { key: 'img', label: 'Logo / image', ico: 'image', upload: 'image' },
      { key: 'sig', label: 'Signature image', ico: 'sig', upload: 'signature' },
      { key: 'sigdraw', label: 'Draw a signature', ico: 'pen', draw: true },
      { key: 'lib', label: 'Saved images (' + libItems.length + ')', ico: 'lib', library: true },
      { key: 'udlogo', label: 'Upper Deck logo (navy)', ico: 'udlogo', make: () => ({ id: CE.uid(), type: 'image', name: 'Upper Deck logo', src: 'assets/tud-logo-navy.png', fit: 'contain', w: 160, h: 50, opacity: 1 }) },
      { key: 'udlogo-w', label: 'Upper Deck logo (white)', ico: 'udlogo', make: () => ({ id: CE.uid(), type: 'image', name: 'Upper Deck logo (white)', src: 'assets/tud-logo-white.png', fit: 'contain', w: 160, h: 50, opacity: 1 }) },
    ] },
    { group: 'Frames', items: CE.FRAME_STYLES.map((f) => ({ key: 'fr-' + f.value, label: f.label, ico: 'fr-' + f.value, full: true, make: () => { const pg = designRef.current.page; return { id: CE.uid(), type: 'frame', name: f.label + ' frame', style: f.value, color: CE.BRAND.orange, thickness: 2, inset: 0, x: 20, y: 20, w: pg.w - 40, h: pg.h - 40, opacity: 1 }; } })) },
    { group: 'Lines & shapes', items: [
      { key: 'line', label: 'Line', ico: 'line', make: () => ({ id: CE.uid(), type: 'line', name: 'Line', color: CE.BRAND.orange, thickness: 2, dashed: false, w: 240, h: 8, opacity: 1 }) },
      { key: 'rect', label: 'Rectangle', ico: 'rect', make: () => ({ id: CE.uid(), type: 'shape', name: 'Rectangle', shape: 'rect', fill: CE.BRAND.navy, stroke: CE.BRAND.navy, strokeWidth: 0, radius: 0, w: 200, h: 120, opacity: 1 }) },
      { key: 'ellipse', label: 'Ellipse', ico: 'ellipse', make: () => ({ id: CE.uid(), type: 'shape', name: 'Ellipse', shape: 'ellipse', fill: CE.BRAND.orange, stroke: CE.BRAND.orange, strokeWidth: 0, w: 120, h: 120, opacity: 1 }) },
      { key: 'dline', label: 'Dashed line', ico: 'dline', make: () => ({ id: CE.uid(), type: 'line', name: 'Dashed line', color: CE.BRAND.navy, thickness: 1.5, dashed: true, w: 240, h: 8, opacity: 1 }) },
      { key: 'line2', label: 'Double line', ico: 'line2', make: () => ({ id: CE.uid(), type: 'line', name: 'Double line', color: CE.BRAND.orange, thickness: 1, lineStyle: 'double', dashed: false, w: 240, h: 10, opacity: 1 }) },
      { key: 'rrect', label: 'Rounded box', ico: 'rrect', make: () => ({ id: CE.uid(), type: 'shape', name: 'Rounded box', shape: 'rect', fill: 'transparent', stroke: CE.BRAND.navy, strokeWidth: 1.5, radius: 14, w: 220, h: 110, opacity: 1 }) },
      { key: 'hexagon', label: 'Hexagon', ico: 'hexagon', make: () => ({ id: CE.uid(), type: 'shape', name: 'Hexagon', shape: 'hexagon', fill: CE.BRAND.navy, stroke: CE.BRAND.navy, strokeWidth: 0, w: 90, h: 80, opacity: 1 }) },
      { key: 'arrow', label: 'Arrow', ico: 'arrow', make: () => ({ id: CE.uid(), type: 'shape', name: 'Arrow', shape: 'arrow', fill: CE.BRAND.orange, stroke: CE.BRAND.orange, strokeWidth: 0, w: 120, h: 70, opacity: 1 }) },
      { key: 'diamond', label: 'Diamond', ico: 'diamond', make: () => ({ id: CE.uid(), type: 'shape', name: 'Diamond', shape: 'diamond', fill: CE.BRAND.orange, stroke: CE.BRAND.orange, strokeWidth: 0, w: 60, h: 60, opacity: 1 }) },
      { key: 'triangle', label: 'Triangle', ico: 'triangle', make: () => ({ id: CE.uid(), type: 'shape', name: 'Triangle', shape: 'triangle', fill: CE.BRAND.navy, stroke: CE.BRAND.navy, strokeWidth: 0, w: 70, h: 60, opacity: 1 }) },
    ] },
  ];
  function pointToPage(ev) {
    const c = canvasRef.current; if (!c) return null;
    const r = c.getBoundingClientRect();
    if (ev.clientX < r.left || ev.clientX > r.right || ev.clientY < r.top || ev.clientY > r.bottom) return null;
    return { x: (ev.clientX - r.left) / zoomRef.current, y: (ev.clientY - r.top) / zoomRef.current };
  }
  function dropPal(item, pt) {
    if (item.library) { setLibOpen(true); return; }
    if (item.draw) { setSigPad({ pt }); return; }
    if (item.upload) { pendingPos.current = pt; imgTarget.current = item.upload; imgInput.current.click(); return; }
    if (item.block) {
      const els = CE.blockEls(item.block), b = selBox(els), pg = designRef.current.page;
      const cx = pt ? pt.x : pg.w / 2, cy = pt ? pt.y : pg.h * 0.72;
      const ox = Math.max(0, Math.min(pg.w - b.w, cx - b.w / 2)) - b.x, oy = Math.max(0, Math.min(pg.h - b.h, cy - b.h / 2)) - b.y;
      addMany(els.map((e) => ({ ...e, x: e.x + ox, y: e.y + oy })));
      return;
    }
    const el = item.make();
    if (pt && !item.full) { const pg = designRef.current.page; el.x = Math.max(0, Math.min(pg.w - el.w, pt.x - el.w / 2)); el.y = Math.max(0, Math.min(pg.h - el.h, pt.y - el.h / 2)); }
    addEl(el);
  }
  function palDown(e, item) {
    if (e.button !== 0) return;
    const sx = e.clientX, sy = e.clientY; let dragging = false;
    const move = (ev) => {
      if (!dragging && Math.abs(ev.clientX - sx) + Math.abs(ev.clientY - sy) > 6) { dragging = true; document.body.style.userSelect = 'none'; }
      if (dragging) setPalGhost({ x: ev.clientX, y: ev.clientY, item, over: !!pointToPage(ev) });
    };
    const up = (ev) => {
      window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', up);
      document.body.style.userSelect = '';
      if (!dragging) return;
      setPalGhost(null);
      suppressPalClick.current = true; setTimeout(() => { suppressPalClick.current = false; }, 0);
      const pt = pointToPage(ev);
      if (pt) dropPal(item, pt);
    };
    window.addEventListener('pointermove', move); window.addEventListener('pointerup', up);
  }
  const palette = (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18, padding: 14 }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 3, paddingBottom: 12, borderBottom: '1px solid var(--border-default)' }}>
        <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: 15, color: 'var(--navy-900)' }}>Elements</div>
        <div style={{ fontSize: 11.5, color: 'var(--text-muted)', lineHeight: 1.4 }}>Click to add, or drag one onto the certificate.</div>
      </div>
      {layoutLocked && <div style={{ fontSize: 12, padding: '8px 10px', borderRadius: 8, background: 'var(--bg-sunken)', color: 'var(--navy-900)', fontWeight: 600 }}>Layout is locked, so new elements can't be added.</div>}
      <div style={{ position: 'relative' }}>
        <svg width="14" height="14" viewBox="0 0 16 16" style={{ position: 'absolute', left: 10, top: 11, color: 'var(--text-muted)' }}><circle cx="7" cy="7" r="4.5" fill="none" stroke="currentColor" strokeWidth="1.6" /><path d="M10.5 10.5L14 14" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" /></svg>
        <input className="ce-input" value={palSearch} onChange={(e) => setPalSearch(e.target.value)} placeholder="Search elements" style={{ ...certEdStyles.input, paddingLeft: 30, paddingRight: palSearch ? 28 : 11 }} />
        {palSearch && <button type="button" aria-label="Clear search" onClick={() => setPalSearch('')} style={{ position: 'absolute', right: 6, top: 7, width: 22, height: 22, border: 'none', background: 'var(--bg-sunken)', borderRadius: 6, cursor: 'pointer', color: 'var(--text-muted)' }}>×</button>}
      </div>
      {palGroups.map((g) => ({ ...g, items: g.items.filter((it) => !palSearch.trim() || (it.label + ' ' + g.group).toLowerCase().indexOf(palSearch.trim().toLowerCase()) !== -1) })).filter((g) => g.items.length).map((g) => (
        <div key={g.group} style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          <div style={certEdStyles.label}>{g.group}</div>
          {g.items.map((it) => (
            <button key={it.key} type="button" className="ce-btn ce-pal" style={{ ...certEdStyles.palBtn, padding: '0 10px 0 6px', minHeight: 40, cursor: 'grab', touchAction: 'none' }}
              onPointerDown={(e) => palDown(e, it)}
              onClick={() => { if (suppressPalClick.current) return; dropPal(it, null); }}>
              <CertPalIcon k={it.ico} />
              <span style={{ minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{it.label}</span>
            </button>
          ))}
        </div>
      ))}
    </div>
  );

  const pagePanel = (
    <>
      <div style={certEdStyles.section}>
        <div style={{ fontWeight: 700, fontSize: 14 }}>Template details</div>
        <CertField label="What is this design for?"><CertSelect value={(design.settings && design.settings.docType) || 'certificate'} onChange={(v) => { const d = designRef.current; commit({ ...d, settings: { ...(d.settings || {}), docType: v } }); }} options={Object.keys(CE.DOC_TYPES).map((k) => ({ value: k, label: CE.DOC_TYPES[k].label }))} /></CertField>
        <CertField label="Short description"><textarea className="ce-input" rows={2} value={description} onChange={(e) => { setDescription(e.target.value); setDirty(true); }} placeholder="Optional, e.g. For IMC Day 1 attendees" style={{ ...certEdStyles.input, height: 'auto', padding: '8px 11px', lineHeight: 1.4, resize: 'vertical' }} /></CertField>
      </div>
      {!layoutLocked && <div style={certEdStyles.section}>
        <div style={{ fontWeight: 700, fontSize: 14 }}>Page</div>
        <CertField label="Size">
          <CertSelect value={design.page.size} onChange={(size) => { const dims = size === 'custom' ? { w: design.page.w, h: design.page.h } : CE.pageDims(size, design.page.orientation); changePage({ size, ...dims }); }} options={[{ value: 'a4', label: 'A4 (210 × 297 mm)' }, { value: 'letter', label: 'Letter (8.5 × 11 in)' }, { value: 'custom', label: 'Custom size' }]} />
        </CertField>
        <CertToggle label="Resize the design when changing paper size" checked={rescaleOn} onChange={setRescaleOn} />
        {design.page.size !== 'custom' ? (
          <CertField label="Orientation"><CertSeg value={design.page.orientation} options={[{ value: 'landscape', label: 'Landscape' }, { value: 'portrait', label: 'Portrait' }]} onChange={(o) => changePage({ orientation: o, ...CE.pageDims(design.page.size, o) })} /></CertField>
        ) : (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            <CertField label="Width (mm)"><CertNum value={design.page.w / CE.MM} onChange={(v) => setPage({ w: Math.max(50, v) * CE.MM, orientation: v * CE.MM > design.page.h ? 'landscape' : 'portrait' })} /></CertField>
            <CertField label="Height (mm)"><CertNum value={design.page.h / CE.MM} onChange={(v) => setPage({ h: Math.max(50, v) * CE.MM, orientation: design.page.w > v * CE.MM ? 'landscape' : 'portrait' })} /></CertField>
          </div>
        )}
      </div>
      }
      {!layoutLocked && <div style={certEdStyles.section}>
        <div style={{ fontWeight: 700, fontSize: 14 }}>Background</div>
        <CertSeg value={design.background.type === 'pdf' ? 'image' : design.background.type} options={[{ value: 'color', label: 'Color' }, { value: 'gradient', label: 'Gradient' }, { value: 'image', label: 'Image / PDF' }]} onChange={(t) => setBg(t === 'image' ? { type: design.background.image ? design.background.type === 'pdf' ? 'pdf' : 'image' : 'image' } : { type: t, color: design.background.color || '#ffffff', color2: design.background.color2 || CE.BRAND.navy2 })} />
        {design.background.type === 'color' && <CertField label="Color"><CertColor value={design.background.color} onChange={(v) => setBg({ color: v }, 'bgc')} /></CertField>}
        {design.background.type === 'gradient' && (
          <>
            <CertField label="From"><CertColor value={design.background.color} onChange={(v) => setBg({ color: v }, 'bgc')} /></CertField>
            <CertField label="To"><CertColor value={design.background.color2} onChange={(v) => setBg({ color2: v }, 'bgc2')} /></CertField>
            <CertField label="Angle"><CertSlider min={0} max={360} step={1} unit="°" value={design.background.angle == null ? 135 : design.background.angle} onChange={(v) => setBg({ angle: v }, 'bga')} /></CertField>
          </>
        )}
        {(design.background.type === 'image' || design.background.type === 'pdf') && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {design.background.type === 'pdf' && design.background.fileName && <div style={{ fontSize: 12, color: 'var(--text-secondary)' }}>Using page 1 of <strong>{design.background.fileName}</strong>. The page size now matches the PDF.</div>}
            <button type="button" className="ce-btn" style={certEdStyles.palBtn} onClick={() => bgImgInput.current.click()}>Upload background image</button>
            <button type="button" className="ce-btn" style={certEdStyles.palBtn} onClick={() => bgPdfInput.current.click()}>Use a PDF as the template</button>
            <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>Word file? Open it in Word, choose File → Save as PDF, then upload the PDF.</div>
            {design.background.image && <>
              <CertField label="Fade the background"><CertSlider min={0} max={0.9} step={0.01} scale={100} unit="%" value={design.background.fade || 0} onChange={(v) => setBg({ fade: v }, 'bgf')} /></CertField>
              {(design.background.fade || 0) > 0 && <CertField label="Fade towards"><CertSeg value={design.background.fadeColor || '#FFFFFF'} options={[{ value: '#FFFFFF', label: 'White' }, { value: '#FBF7EF', label: 'Ivory' }, { value: '#0E2247', label: 'Navy' }, { value: '#000000', label: 'Black' }]} onChange={(v) => setBg({ fadeColor: v })} /></CertField>}
            </>}
          </div>
        )}
      </div>
      }
      {!layoutLocked && <div style={certEdStyles.section}>
        <div style={{ fontWeight: 700, fontSize: 14 }}>Colours & fonts</div>
        <CertField label="Colour scheme (one click)">
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, minmax(0,1fr))', gap: 6 }}>
            {CE.SCHEMES.map((sc) => <button key={sc.key} type="button" title={sc.name} className="ce-btn" onClick={() => { commit(CE.applyScheme(designRef.current, sc)); flash(sc.name + ' applied. Press Undo to go back.'); }} style={{ height: 40, border: '1.5px solid var(--border-default)', borderRadius: 8, cursor: 'pointer', background: sc.light, display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 3, padding: 0 }}><span style={{ width: 14, height: 14, borderRadius: '50%', background: sc.dark }}></span><span style={{ width: 14, height: 14, borderRadius: '50%', background: sc.accent }}></span></button>)}
          </div>
        </CertField>
        <CertField label="Colours used: click one to change it everywhere">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {CE.collectColors(design).map((col, i) => <CertColor key={'cu' + i} value={col} onChange={(v) => { if (!/^#[0-9a-f]{6}$/i.test(v)) return; commit(CE.replaceColor(designRef.current, col, v), 'swap' + i); }} />)}
          </div>
        </CertField>
        <CertField label="Fonts used: change one everywhere">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {CE.collectFonts(design).map((f, i) => <CertSelect key={'fu' + i} fontPreview value={f} onChange={(v) => { if (v !== f) { commit(CE.replaceFont(designRef.current, f, v)); flash('Every "' + f + '" is now "' + v + '".'); } }} options={CE.FONTS.map((x) => ({ value: x.value, label: x.label }))} />)}
            {CE.collectFonts(design).length === 0 && <div style={{ fontSize: 12, color: 'var(--text-muted)' }}>No text yet.</div>}
          </div>
        </CertField>
      </div>}
      <div style={certEdStyles.section}>
        <div style={{ fontWeight: 700, fontSize: 14 }}>Printing & layout help</div>
        <CertToggle label={'Show print-safe area (' + CE.SAFE_MM + ' mm from the edge)'} checked={showSafe} onChange={setShowSafe} />
        <CertToggle label="Show rulers (mm)" checked={showRulers} onChange={setShowRulers} />
        <CertToggle label="Snap to grid" checked={grid.on} onChange={(v) => setGrid((g) => ({ ...g, on: v }))} />
        {grid.on && <CertField label="Grid size"><CertSeg value={grid.mm} options={[{ value: 2, label: '2 mm' }, { value: 5, label: '5 mm' }, { value: 10, label: '10 mm' }]} onChange={(v) => setGrid((g) => ({ ...g, mm: v }))} /></CertField>}
        {unsafe.length > 0 ? (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, padding: '10px 12px', borderRadius: 8, background: 'color-mix(in srgb, var(--status-warning, #D98E04) 10%, white)', border: '1px solid color-mix(in srgb, var(--status-warning, #D98E04) 35%, white)' }}>
            <div style={{ fontSize: 12.5, fontWeight: 600, color: '#7a4f00' }}>{unsafe.length} element{unsafe.length === 1 ? ' is' : 's are'} too close to the edge</div>
            <div style={{ fontSize: 11.5, color: '#7a4f00', lineHeight: 1.45 }}>Most office printers can't print right to the edge, so these may get cut off. Move them inside the dashed line.</div>
            <button type="button" className="ce-btn" style={{ ...certEdStyles.iconBtn, alignSelf: 'flex-start' }} onClick={() => { setSelIds(unsafe.map((u) => u.id)); }}>Select them</button>
          </div>
        ) : <div style={{ fontSize: 12, color: 'var(--status-success)', fontWeight: 600 }}>Everything is inside the print-safe area.</div>}
      </div>
      <div style={{ ...certEdStyles.section, borderBottom: 'none', fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.5 }}>
        Click an element on the page to edit it. Drag to move, pull the corner handles to resize (hold Shift to keep proportions). Snapping to the centre and other elements is on; hold Alt to place freely.
      </div>
    </>
  );

  const alignBtns = (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, minmax(0,1fr))', gap: 6 }}>
      {[['left', 'aLeft', 'Align left'], ['hcenter', 'aHc', 'Align centre'], ['right', 'aRight', 'Align right'], ['top', 'aTop', 'Align top'], ['vmiddle', 'aVm', 'Align middle'], ['bottom', 'aBot', 'Align bottom']].map((a) => (
        <button key={a[0]} type="button" title={a[2]} className="ce-btn" onClick={() => alignSel(a[0])} style={{ ...certEdStyles.iconBtn, minWidth: 0, padding: 0 }}><CertIcon d={CERT_ICONS[a[1]]} /></button>
      ))}
    </div>
  );
  const selEls = design.elements.filter((e) => selIds.indexOf(e.id) !== -1);
  const multiPanel = multi && (
    <>
      <div style={certEdStyles.section}>
        <div style={{ fontWeight: 700, fontSize: 14 }}>{selIds.length} elements selected</div>
        <div style={{ fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.45 }}>{layoutLocked ? 'The layout is locked, so these can\'t be moved or changed together.' : 'Drag any of them to move them together, or pull the corner handles to resize them as one.'}</div>
        {!layoutLocked && (selEls.length > 1 && selEls.every((x) => x.group && x.group === selEls[0].group)
          ? <button type="button" className="ce-btn" style={certEdStyles.iconBtn} onClick={ungroupSel}><CertIcon d="M3 3h5v5H3zM8 8h5v5H8z" />Ungroup</button>
          : <button type="button" className="ce-btn" style={{ ...certEdStyles.iconBtn, background: 'var(--navy-900)', color: 'white', borderColor: 'var(--navy-900)' }} onClick={groupSel}><CertIcon d="M2.5 2.5h11v11h-11zM5 5h3v3H5zM8 8h3v3H8z" />Group these</button>)}
      </div>
      {!layoutLocked && <><div style={certEdStyles.section}>
        <span style={certEdStyles.label}>Line them up</span>
        {alignBtns}
        <span style={{ ...certEdStyles.label, marginTop: 4 }}>Space them evenly</span>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          <button type="button" className="ce-btn" disabled={selEls.length < 3} onClick={() => distributeSel('h')} style={{ ...certEdStyles.iconBtn, opacity: selEls.length < 3 ? 0.45 : 1 }}><CertIcon d={CERT_ICONS.dH} />Left to right</button>
          <button type="button" className="ce-btn" disabled={selEls.length < 3} onClick={() => distributeSel('v')} style={{ ...certEdStyles.iconBtn, opacity: selEls.length < 3 ? 0.45 : 1 }}><CertIcon d={CERT_ICONS.dV} />Top to bottom</button>
        </div>
        {selEls.length < 3 && <div style={{ fontSize: 11, color: 'var(--text-muted)' }}>Select 3 or more to space them evenly.</div>}
      </div>
      <div style={{ ...certEdStyles.section, borderBottom: 'none' }}>
        <span style={certEdStyles.label}>Arrange</span>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          <button type="button" className="ce-btn" style={{ ...certEdStyles.iconBtn, flexDirection: 'column', height: 58, gap: 5, fontSize: 12.5 }} onClick={() => reorderSel('forward')}><CertIcon d={CERT_ICONS.up} />Bring forward</button>
          <button type="button" className="ce-btn" style={{ ...certEdStyles.iconBtn, flexDirection: 'column', height: 58, gap: 5, fontSize: 12.5 }} onClick={() => reorderSel('backward')}><CertIcon d={CERT_ICONS.down} />Send back</button>
          <button type="button" className="ce-btn" style={{ ...certEdStyles.iconBtn, flexDirection: 'column', height: 58, gap: 5, fontSize: 12.5 }} onClick={duplicateSel}><CertIcon d={CERT_ICONS.dup} />Duplicate</button>
          <button type="button" className="ce-btn" style={{ ...certEdStyles.iconBtn, flexDirection: 'column', height: 58, gap: 5, fontSize: 12.5 }} onClick={() => patchSel({ locked: true })}><CertIcon d={CERT_ICONS.lock} />Lock all</button>
        </div>
        <button type="button" className="ce-btn-danger" style={{ ...certEdStyles.iconBtn, width: '100%', color: 'var(--status-error)', borderColor: 'color-mix(in srgb, var(--status-error) 35%, white)', background: 'color-mix(in srgb, var(--status-error) 6%, white)' }} onClick={removeSel}><CertIcon d={CERT_ICONS.del} />Delete {selIds.length} elements</button>
      </div></>}
    </>
  );
  const isText = sel && (sel.type === 'text' || sel.type === 'field');
  const lockedElPanel = sel && (
    <div style={certEdStyles.section}>
      <div style={{ fontWeight: 700, fontSize: 14 }}>{sel.name || sel.type}</div>
      {sel.type === 'text' ? (
        <CertField label="Wording">
          <textarea spellCheck={true} lang="en" ref={textRef} rows={4} value={sel.text} onChange={(e) => updateEl(sel.id, { text: e.target.value }, 'text')} className="ce-input" style={{ ...certEdStyles.input, height: 'auto', padding: '9px 11px', lineHeight: 1.45, resize: 'vertical' }} />
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 6, textTransform: 'none', letterSpacing: 0 }}>
            {Object.keys(CE.FIELDS).map((k) => <button key={k} type="button" className="ce-chip" onMouseDown={(e) => e.preventDefault()} onClick={(e) => { e.preventDefault(); insertToken(k); }} style={{ display: 'inline-flex', alignItems: 'center', gap: 4, height: 28, padding: '0 10px', borderRadius: 999, border: '1.5px solid color-mix(in srgb, var(--brand-primary) 45%, white)', background: 'color-mix(in srgb, var(--brand-primary) 9%, white)', color: 'var(--navy-900)', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'var(--font-body)' }}><span style={{ color: 'var(--brand-primary)', fontWeight: 800 }}>+</span>{CE.FIELDS[k].label}</button>)}
          </div>
        </CertField>
      ) : sel.type === 'field' ? (
        <CertField label="Auto-filled value"><CertSelect value={sel.field} onChange={(f) => updateEl(sel.id, { field: f, name: CE.FIELDS[f].label })} options={Object.keys(CE.FIELDS).map((k) => ({ value: k, label: CE.FIELDS[k].label }))} /></CertField>
      ) : <div style={{ fontSize: 12.5, color: 'var(--text-muted)', lineHeight: 1.45 }}>The layout is locked, so this element can't be changed. Only text and auto-filled details can be edited.</div>}
    </div>
  );
  const elPanel = sel && (
    <>
      <div style={{ ...certEdStyles.section, flexDirection: 'row', alignItems: 'center', gap: 8 }}>
        <input value={sel.name || ''} onChange={(e) => updateEl(sel.id, { name: e.target.value }, 'name')} className="ce-input" style={{ ...certEdStyles.input, fontWeight: 700 }} aria-label="Layer name" />
        <button type="button" title="Done" onClick={() => setSelId(null)} className="ce-btn" style={{ ...certEdStyles.iconBtn, background: 'var(--navy-900)', color: 'white', borderColor: 'var(--navy-900)' }}>✓</button>
      </div>
      {isText && (
        <div style={certEdStyles.section}>
          {sel.type === 'text' ? (
            <CertField label="Text">
              <textarea spellCheck={true} lang="en" ref={textRef} rows={3} value={sel.text} onChange={(e) => updateEl(sel.id, { text: e.target.value }, 'text')} className="ce-input" style={{ ...certEdStyles.input, height: 'auto', padding: '9px 11px', lineHeight: 1.45, resize: 'vertical' }} />
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginTop: 4, textTransform: 'none', letterSpacing: 0 }}>
                <span style={{ fontSize: 12, fontWeight: 600, color: 'var(--navy-900)' }}>Add a detail that fills in for each person</span>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                  {Object.keys(CE.FIELDS).map((k) => (
                    <button key={k} type="button" className="ce-chip" onMouseDown={(e) => e.preventDefault()} onClick={(e) => { e.preventDefault(); insertToken(k); }} style={{ display: 'inline-flex', alignItems: 'center', gap: 4, height: 28, padding: '0 10px', borderRadius: 999, border: '1.5px solid color-mix(in srgb, var(--brand-primary) 45%, white)', background: 'color-mix(in srgb, var(--brand-primary) 9%, white)', color: 'var(--navy-900)', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'var(--font-body)' }}><span style={{ color: 'var(--brand-primary)', fontWeight: 800 }}>+</span>{CE.FIELDS[k].label}</button>
                  ))}
                </div>
                <span style={{ fontSize: 11, color: 'var(--text-muted)', fontWeight: 400, lineHeight: 1.4 }}>Click one to add it where your cursor is. It shows as a word in curly brackets here, and becomes the real name, date or title on each certificate.</span>
              </div>
            </CertField>
          ) : (
            <CertField label="Auto-filled value">
              <CertSelect value={sel.field} onChange={(f) => updateEl(sel.id, { field: f, name: CE.FIELDS[f].label })} options={Object.keys(CE.FIELDS).map((k) => ({ value: k, label: CE.FIELDS[k].label }))} />
            </CertField>
          )}
          <CertField label="Font">
            <CertSelect fontPreview value={sel.fontFamily} onChange={(f) => updateEl(sel.id, { fontFamily: f })} options={CE.FONTS.map((f) => ({ value: f.value, label: f.label }))} />
          </CertField>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            <CertField label="Size"><CertNum value={sel.fontSize} min={4} onChange={(v) => updateEl(sel.id, { fontSize: Math.max(4, v) }, 'fs')} /></CertField>
            <CertField label="Letter spacing"><CertNum value={sel.letterSpacing} step={0.5} onChange={(v) => updateEl(sel.id, { letterSpacing: v }, 'ls')} /></CertField>
          </div>
          <div style={{ display: 'flex', gap: 6 }}>
            <button type="button" onClick={() => updateEl(sel.id, { bold: !sel.bold })} style={{ ...certEdStyles.iconBtn, fontWeight: 700, background: sel.bold ? 'var(--navy-900)' : 'white', color: sel.bold ? 'white' : 'var(--text-primary)' }}>B</button>
            <button type="button" onClick={() => updateEl(sel.id, { italic: !sel.italic })} style={{ ...certEdStyles.iconBtn, fontStyle: 'italic', background: sel.italic ? 'var(--navy-900)' : 'white', color: sel.italic ? 'white' : 'var(--text-primary)' }}>I</button>
            <button type="button" title="Underline" onClick={() => updateEl(sel.id, { underline: !sel.underline })} style={{ ...certEdStyles.iconBtn, textDecoration: 'underline', background: sel.underline ? 'var(--navy-900)' : 'white', color: sel.underline ? 'white' : 'var(--text-primary)' }}>U</button>
            
          </div>
          <CertField label="Alignment"><CertSeg value={sel.align} options={[{ value: 'left', label: 'Left' }, { value: 'center', label: 'Center' }, { value: 'right', label: 'Right' }]} onChange={(v) => updateEl(sel.id, { align: v })} /></CertField>
          <CertField label="Color"><CertColor value={sel.color} onChange={(v) => updateEl(sel.id, { color: v }, 'col')} /></CertField>
          <CertToggle label="Shrink to fit (for long names)" checked={sel.autoShrink} onChange={(v) => updateEl(sel.id, { autoShrink: v })} />
          <div style={{ borderTop: '1px solid var(--border-default)', paddingTop: 12, display: 'flex', flexDirection: 'column', gap: 10 }}>
            <span style={certEdStyles.label}>Text effects</span>
            <CertToggle label="Shadow" checked={!!(sel.shadow && sel.shadow.on)} onChange={(v) => updateEl(sel.id, { shadow: { color: 'rgba(0,0,0,0.45)', blur: 6, x: 0, y: 2, ...(sel.shadow || {}), on: v } })} />
            {sel.shadow && sel.shadow.on && (
              <>
                <CertField label="Shadow colour"><CertColor value={sel.shadow.color} onChange={(v) => updateEl(sel.id, { shadow: { ...sel.shadow, color: v } }, 'shc')} /></CertField>
                <CertField label="Softness"><CertSlider min={0} max={30} step={1} unit="pt" value={sel.shadow.blur == null ? 6 : sel.shadow.blur} onChange={(v) => updateEl(sel.id, { shadow: { ...sel.shadow, blur: v } }, 'shb')} /></CertField>
                <CertField label="Distance"><CertSlider min={0} max={20} step={0.5} unit="pt" value={sel.shadow.y == null ? 2 : sel.shadow.y} onChange={(v) => updateEl(sel.id, { shadow: { ...sel.shadow, y: v, x: v * 0.4 } }, 'shy')} /></CertField>
              </>
            )}
            <CertToggle label="Outline" checked={!!(sel.outline && sel.outline.on)} onChange={(v) => updateEl(sel.id, { outline: { color: '#FFFFFF', width: 2, ...(sel.outline || {}), on: v } })} />
            {sel.outline && sel.outline.on && (
              <>
                <CertField label="Outline colour"><CertColor value={sel.outline.color} onChange={(v) => updateEl(sel.id, { outline: { ...sel.outline, color: v } }, 'olc')} /></CertField>
                <CertField label="Outline thickness"><CertSlider min={0.5} max={8} step={0.5} unit="pt" value={sel.outline.width == null ? 2 : sel.outline.width} onChange={(v) => updateEl(sel.id, { outline: { ...sel.outline, width: v } }, 'olw')} /></CertField>
              </>
            )}
          </div>
        </div>
      )}
      {sel.type === 'image' && (
        <div style={certEdStyles.section}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            <button type="button" className="ce-btn" style={certEdStyles.iconBtn} onClick={() => { imgTarget.current = 'replace'; imgInput.current.click(); }}>Replace</button>
            <button type="button" className="ce-btn" style={certEdStyles.iconBtn} onClick={() => setCropFor(sel.id)}>Crop{sel.crop ? ' (on)' : ''}</button>
          </div>
          <button type="button" className="ce-btn" disabled={bgBusy} style={{ ...certEdStyles.iconBtn, width: '100%' }} title="Makes white and near-white paper see-through, e.g. for scanned signatures" onClick={async () => { setBgBusy(true); try { const out = await CE.removeWhiteBg(CE.srcOf(sel.src)); const id = CE.putAsset(out); updateEl(sel.id, { src: id }); CE.addToLibrary(id, sel.name === 'Signature' ? 'signature' : 'image', (sel.name || 'Image') + ' (no background)'); setLibItems(CE.loadLibrary()); flash('White background removed. Press Undo to bring it back.'); } catch (e) { flash('Could not process this image.', true); } setBgBusy(false); }}>{bgBusy ? 'Working…' : 'Remove white background'}</button>
          <CertField label="Rounded corners"><CertSlider min={0} max={Math.round(Math.min(sel.w, sel.h) / 2)} step={1} unit="pt" value={Math.min(sel.radius || 0, Math.round(Math.min(sel.w, sel.h) / 2))} onChange={(v) => updateEl(sel.id, { radius: v }, 'irad')} /></CertField>
          <CertField label="Fit"><CertSeg value={sel.fit || 'contain'} options={[{ value: 'contain', label: 'Fit' }, { value: 'cover', label: 'Fill' }, { value: 'stretch', label: 'Stretch' }]} onChange={(v) => updateEl(sel.id, { fit: v })} /></CertField>
        </div>
      )}
      {sel.type === 'frame' && (
        <div style={certEdStyles.section}>
          <CertField label="Style"><CertSelect value={sel.style} onChange={(v) => updateEl(sel.id, { style: v })} options={CE.FRAME_STYLES.map((f) => ({ value: f.value, label: f.label }))} /></CertField>
          <CertField label="Color"><CertColor value={sel.color} onChange={(v) => updateEl(sel.id, { color: v }, 'col')} /></CertField>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            <CertField label="Thickness"><CertNum value={sel.thickness} step={0.5} min={0.5} onChange={(v) => updateEl(sel.id, { thickness: Math.max(0.5, v) }, 'th')} /></CertField>
            <CertField label="Inset"><CertNum value={sel.inset} onChange={(v) => updateEl(sel.id, { inset: Math.max(0, v) }, 'in')} /></CertField>
          </div>
        </div>
      )}
      {sel.type === 'line' && (
        <div style={certEdStyles.section}>
          <CertField label="Color"><CertColor value={sel.color} onChange={(v) => updateEl(sel.id, { color: v }, 'col')} /></CertField>
          <CertField label="Thickness"><CertNum value={sel.thickness} step={0.5} min={0.5} onChange={(v) => updateEl(sel.id, { thickness: Math.max(0.5, v) }, 'th')} /></CertField>
          <CertToggle label="Dashed" checked={sel.dashed} onChange={(v) => updateEl(sel.id, { dashed: v })} />
        </div>
      )}
      {sel.type === 'shape' && (
        <div style={certEdStyles.section}>
          <CertField label="Shape"><CertSeg value={sel.shape} options={[{ value: 'rect', label: 'Rectangle' }, { value: 'ellipse', label: 'Ellipse' }]} onChange={(v) => updateEl(sel.id, { shape: v })} /></CertField>
          <CertField label="Fill"><CertColor value={sel.fill} onChange={(v) => updateEl(sel.id, { fill: v }, 'fill')} /></CertField>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            <CertField label="Border"><CertNum value={sel.strokeWidth} step={0.5} min={0} onChange={(v) => updateEl(sel.id, { strokeWidth: Math.max(0, v) }, 'sw')} /></CertField>
            {sel.shape === 'rect' && <CertField label="Corner radius"><CertNum value={sel.radius} min={0} onChange={(v) => updateEl(sel.id, { radius: Math.max(0, v) }, 'rad')} /></CertField>}
          </div>
          {sel.strokeWidth > 0 && <CertField label="Border color"><CertColor value={sel.stroke} onChange={(v) => updateEl(sel.id, { stroke: v }, 'stc')} /></CertField>}
        </div>
      )}
      <div style={certEdStyles.section}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <CertField label="X (from left)"><CertNum value={sel.x} unit="pt" onChange={(v) => updateEl(sel.id, { x: v }, 'x')} /></CertField>
          <CertField label="Y (from top)"><CertNum value={sel.y} unit="pt" onChange={(v) => updateEl(sel.id, { y: v }, 'y')} /></CertField>
          <CertField label="Width"><CertNum value={sel.w} min={6} unit="pt" onChange={(v) => updateEl(sel.id, { w: Math.max(6, v) }, 'w')} /></CertField>
          <CertField label="Height"><CertNum value={sel.h} min={6} unit="pt" onChange={(v) => updateEl(sel.id, { h: Math.max(6, v) }, 'h')} /></CertField>
          <CertField label="Rotation"><CertNum value={sel.rotation || 0} min={-180} max={180} unit="°" onChange={(v) => updateEl(sel.id, { rotation: v }, 'rot')} /></CertField>
          <div style={{ display: 'flex', alignItems: 'flex-end' }}><button type="button" className="ce-btn" disabled={!sel.rotation} onClick={() => updateEl(sel.id, { rotation: 0 })} style={{ ...certEdStyles.iconBtn, width: '100%', opacity: sel.rotation ? 1 : 0.45 }}>Straighten</button></div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          <span style={certEdStyles.label}>Align on page</span>
          {alignBtns}
          <span style={{ ...certEdStyles.label, marginTop: 4 }}>Center on page</span>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            <button type="button" className="ce-btn" style={certEdStyles.iconBtn} onClick={() => updateEl(sel.id, { x: (W - sel.w) / 2 })}><CertIcon d={CERT_ICONS.ch} />Left–right</button>
            <button type="button" className="ce-btn" style={certEdStyles.iconBtn} onClick={() => updateEl(sel.id, { y: (H - sel.h) / 2 })}><CertIcon d={CERT_ICONS.cv} />Top–bottom</button>
          </div>
        </div>
        <CertField label="Opacity"><CertSlider min={0} max={1} step={0.01} scale={100} unit="%" value={sel.opacity == null ? 1 : sel.opacity} onChange={(v) => updateEl(sel.id, { opacity: v }, 'op')} /></CertField>
      </div>
      <div style={{ ...certEdStyles.section, borderBottom: 'none' }}>
        <span style={certEdStyles.label}>Arrange</span>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          <button type="button" className="ce-btn" style={{ ...certEdStyles.iconBtn, flexDirection: 'column', height: 58, gap: 5, fontSize: 12.5, padding: '0 8px', whiteSpace: 'nowrap', lineHeight: 1.15 }} onClick={() => moveLayer(sel.id, 1)}><CertIcon d={CERT_ICONS.up} />Bring forward</button>
          <button type="button" className="ce-btn" style={{ ...certEdStyles.iconBtn, flexDirection: 'column', height: 58, gap: 5, fontSize: 12.5, padding: '0 8px', whiteSpace: 'nowrap', lineHeight: 1.15 }} onClick={() => moveLayer(sel.id, -1)}><CertIcon d={CERT_ICONS.down} />Send back</button>
          <button type="button" className="ce-btn" style={{ ...certEdStyles.iconBtn, flexDirection: 'column', height: 58, gap: 5, fontSize: 12.5, padding: '0 8px', whiteSpace: 'nowrap', lineHeight: 1.15 }} onClick={duplicateSel}><CertIcon d={CERT_ICONS.dup} />Duplicate</button>
          <button type="button" className="ce-btn" style={{ ...certEdStyles.iconBtn, flexDirection: 'column', height: 58, gap: 5, fontSize: 12.5, padding: '0 8px', whiteSpace: 'nowrap', lineHeight: 1.15, ...(sel.locked ? { background: 'var(--navy-900)', color: 'white', borderColor: 'var(--navy-900)' } : {}) }} onClick={() => updateEl(sel.id, { locked: !sel.locked })}><CertIcon d={sel.locked ? CERT_ICONS.lock : CERT_ICONS.unlock} />{sel.locked ? 'Locked' : 'Lock'}</button>
        </div>
        <button type="button" className="ce-btn-danger" style={{ ...certEdStyles.iconBtn, width: '100%', color: 'var(--status-error)', borderColor: 'color-mix(in srgb, var(--status-error) 35%, white)', background: 'color-mix(in srgb, var(--status-error) 6%, white)' }} onClick={removeSel}><CertIcon d={CERT_ICONS.del} />Delete element</button>
      </div>
    </>
  );

  function layerDown(e, el, ri) {
    if (e.button !== 0 || e.target.closest('button')) return;
    if (layoutLockedRef.current) { setSelId(el.id); setTab('props'); return; }
    const sy = e.clientY; let dragging = false, lastLayerDrag = null;
    const move = (ev) => {
      if (!dragging && Math.abs(ev.clientY - sy) > 5) { dragging = true; document.body.style.userSelect = 'none'; }
      if (!dragging) return;
      const rev = designRef.current.elements.slice().reverse();
      let over = rev.length;
      for (let k = 0; k < rev.length; k++) { const node = layerRows.current[rev[k].id]; if (!node) continue; const r = node.getBoundingClientRect(); if (ev.clientY < r.top + r.height / 2) { over = k; break; } }
      const ld = { id: el.id, from: ri, over }; lastLayerDrag = ld; setLayerDrag(ld);
    };
    const up = () => {
      window.removeEventListener('pointermove', move); window.removeEventListener('pointerup', up);
      document.body.style.userSelect = '';
      if (!dragging) { if (e.shiftKey) setSelIds((cur) => (cur.indexOf(el.id) !== -1 ? cur.filter((x) => x !== el.id) : cur.concat([el.id]))); else setSelId(el.id); return; }
      const ld = lastLayerDrag; setLayerDrag(null);
      if (ld) {
        const d = designRef.current, rev = d.elements.slice().reverse();
        let to = ld.over; if (to > ld.from) to -= 1;
        if (to !== ld.from) { const [m] = rev.splice(ld.from, 1); rev.splice(to, 0, m); commit({ ...d, elements: rev.reverse() }); setSelId(el.id); }
      }
    };
    window.addEventListener('pointermove', move); window.addEventListener('pointerup', up);
  }
  const lyBtn = { ...certEdStyles.iconBtn, minWidth: 28, width: 28, height: 28, padding: 0, borderRadius: 7 };
  const layersPanel = (
    <div style={{ display: 'flex', flexDirection: 'column' }}>
      <div style={{ padding: '10px 14px', fontSize: 11.5, color: 'var(--text-muted)', borderBottom: '1px solid var(--border-default)', background: 'var(--bg-sunken)' }}>Top of the list sits on top. Drag a row to reorder.</div>
      {design.elements.length === 0 && <div style={{ padding: 16, fontSize: 13, color: 'var(--text-muted)' }}>No elements yet. Add some from the left.</div>}
      {design.elements.slice().reverse().map((el, ri) => {
        const i = design.elements.length - 1 - ri;
        const isDrag = layerDrag && layerDrag.id === el.id;
        const showLine = layerDrag && layerDrag.over === ri && layerDrag.from !== ri && layerDrag.from !== ri - 1;
        return (
          <div key={el.id} ref={(n) => { layerRows.current[el.id] = n; }} onPointerDown={(e) => layerDown(e, el, ri)} className="ce-layer" style={{ position: 'relative', display: 'flex', alignItems: 'center', gap: 6, padding: '8px 10px 8px 6px', borderBottom: '1px solid var(--border-default)', cursor: layerDrag ? 'grabbing' : 'grab', background: selIds.indexOf(el.id) !== -1 ? 'color-mix(in srgb, var(--brand-primary) 12%, white)' : 'white', opacity: isDrag ? 0.45 : (el.hidden ? 0.55 : 1), touchAction: 'none' }}>
            {showLine && <span style={{ position: 'absolute', left: 6, right: 6, top: -2, height: 3, borderRadius: 2, background: 'var(--brand-primary)' }}></span>}
            <span aria-hidden="true" style={{ color: 'var(--text-muted)', display: 'flex', flexShrink: 0 }}><svg width="12" height="16" viewBox="0 0 12 16"><circle cx="4" cy="4" r="1.3" fill="currentColor" /><circle cx="8" cy="4" r="1.3" fill="currentColor" /><circle cx="4" cy="8" r="1.3" fill="currentColor" /><circle cx="8" cy="8" r="1.3" fill="currentColor" /><circle cx="4" cy="12" r="1.3" fill="currentColor" /><circle cx="8" cy="12" r="1.3" fill="currentColor" /></svg></span>
            <span style={{ flex: 1, minWidth: 0, fontSize: 13, fontWeight: selIds.indexOf(el.id) !== -1 ? 700 : 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{el.name || el.type}{el.group && <span style={{ marginLeft: 6, fontSize: 10, fontWeight: 700, color: 'var(--brand-primary)', background: 'color-mix(in srgb, var(--brand-primary) 12%, white)', padding: '1px 6px', borderRadius: 999 }}>Group</span>}</span>
            <button type="button" title={el.hidden ? 'Show' : 'Hide'} onClick={(e) => { e.stopPropagation(); updateEl(el.id, { hidden: !el.hidden }); }} className="ce-btn" style={lyBtn}><CertIcon d={el.hidden ? 'M2 8s2.2-4 6-4 6 4 6 4-2.2 4-6 4-6-4-6-4zM3 13L13 3' : 'M2 8s2.2-4 6-4 6 4 6 4-2.2 4-6 4-6-4-6-4zM8 9.6a1.6 1.6 0 100-3.2 1.6 1.6 0 000 3.2z'} /></button>
            <button type="button" title={el.locked ? 'Unlock' : 'Lock'} onClick={(e) => { e.stopPropagation(); updateEl(el.id, { locked: !el.locked }); }} className="ce-btn" style={{ ...lyBtn, ...(el.locked ? { background: 'var(--navy-900)', color: 'white', borderColor: 'var(--navy-900)' } : {}) }}><CertIcon d={el.locked ? CERT_ICONS.lock : CERT_ICONS.unlock} /></button>
            <button type="button" title="Move up" disabled={i === design.elements.length - 1} onClick={(e) => { e.stopPropagation(); moveLayer(el.id, 1); }} className="ce-btn" style={{ ...lyBtn, opacity: i === design.elements.length - 1 ? 0.35 : 1 }}><CertIcon d={CERT_ICONS.up} /></button>
            <button type="button" title="Move down" disabled={i === 0} onClick={(e) => { e.stopPropagation(); moveLayer(el.id, -1); }} className="ce-btn" style={{ ...lyBtn, opacity: i === 0 ? 0.35 : 1 }}><CertIcon d={CERT_ICONS.down} /></button>
          </div>
        );
      })}
      {layerDrag && layerDrag.over === design.elements.length && layerDrag.from !== design.elements.length - 1 && <span style={{ height: 3, margin: '-2px 6px 0', borderRadius: 2, background: 'var(--brand-primary)' }}></span>}
    </div>
  );

  const libShown = libItems.filter((it) => (libKind === 'all' || (libKind === 'signature' ? it.kind === 'signature' : it.kind !== 'signature')) && (!libQ || ((it.name || '') + ' ' + (it.kind || '')).toLowerCase().indexOf(libQ.toLowerCase()) !== -1));
  // ---------- layout ----------
  return ReactDOM.createPortal(
    <div className={'ce-editor' + (leaving ? ' ce-out' : '')} style={{ position: 'fixed', inset: 0, zIndex: 1300, background: 'var(--bg-sunken)', display: 'flex', flexDirection: 'column', fontFamily: 'var(--font-body)' }}>
      {palGhost && (
        <div style={{ position: 'fixed', left: palGhost.x + 12, top: palGhost.y + 12, zIndex: 2200, pointerEvents: 'none', display: 'flex', alignItems: 'center', gap: 8, padding: '6px 12px 6px 6px', background: 'white', border: '1.5px solid ' + (palGhost.over ? 'var(--brand-primary)' : 'var(--border-default)'), borderRadius: 10, boxShadow: '0 10px 24px rgba(5,13,26,.22)', fontSize: 13, fontWeight: 600, color: 'var(--navy-900)', fontFamily: 'var(--font-body)' }}>
          <CertPalIcon k={palGhost.item.ico} />{palGhost.item.label}
          <span style={{ fontSize: 11, fontWeight: 500, color: palGhost.over ? 'var(--brand-primary)' : 'var(--text-muted)', marginLeft: 4 }}>{palGhost.over ? 'Release to place' : 'Drop on the certificate'}</span>
        </div>
      )}
      <input ref={imgInput} type="file" accept="image/*" style={{ display: 'none' }} onChange={(e) => { onImageFile(e.target.files[0]); e.target.value = ''; }} />
      <input ref={bgImgInput} type="file" accept="image/*" style={{ display: 'none' }} onChange={(e) => { onBgImage(e.target.files[0]); e.target.value = ''; }} />
      <input ref={bgPdfInput} type="file" accept="application/pdf,.pdf" style={{ display: 'none' }} onChange={(e) => { onBgPdf(e.target.files[0]); e.target.value = ''; }} />

      <div className="ce-topbar" style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '10px 14px', background: 'var(--navy-950)', color: 'white', flexWrap: 'nowrap', minWidth: 0, overflowX: 'auto', scrollbarWidth: 'none' }}>
        <button type="button" onClick={close} style={{ ...certEdStyles.iconBtn, height: 34, flexShrink: 0, background: 'transparent', color: 'white', borderColor: 'rgba(255,255,255,0.25)' }}>← Back</button>
        <input value={name} onChange={(e) => { setName(e.target.value); setDirty(true); }} placeholder="Template name" aria-label="Template name" style={{ ...certEdStyles.input, height: 34, flex: '1 1 220px', minWidth: 80, maxWidth: 320, background: 'rgba(255,255,255,0.08)', color: 'white', borderColor: 'rgba(255,255,255,0.2)', fontWeight: 600 }} />
        <span className="ce-status" title={versionLabel} style={{ width: 128, flexShrink: 0, fontSize: 11.5, color: dirty ? '#FFD27A' : 'rgba(255,255,255,0.55)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', display: 'flex', alignItems: 'center', gap: 6 }}><span style={{ width: 7, height: 7, borderRadius: '50%', background: dirty ? '#FFB443' : 'rgba(255,255,255,0.35)', flexShrink: 0 }}></span>{dirty ? 'Unsaved changes' : (versionLabel || 'Saved')}</span>
        <span style={{ flex: 1, minWidth: 8 }}></span>
        <div style={{ display: 'flex', gap: 4, flexShrink: 0 }}>
          <button type="button" title="Undo (Ctrl+Z)" aria-label="Undo" disabled={!past.length} onClick={undo} style={{ ...certEdStyles.iconBtn, height: 34, background: 'transparent', color: 'white', borderColor: 'rgba(255,255,255,0.25)', width: 34, padding: 0, opacity: past.length ? 1 : 0.4 }}><CertIcon d="M6 4L3 7l3 3M3 7h6.5a3.5 3.5 0 010 7H7" /></button>
          <button type="button" title="Redo (Ctrl+Shift+Z)" aria-label="Redo" disabled={!future.length} onClick={redo} style={{ ...certEdStyles.iconBtn, height: 34, background: 'transparent', color: 'white', borderColor: 'rgba(255,255,255,0.25)', width: 34, padding: 0, opacity: future.length ? 1 : 0.4 }}><CertIcon d="M10 4l3 3-3 3M13 7H6.5a3.5 3.5 0 000 7H9" /></button>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', flexShrink: 0, border: '1px solid rgba(255,255,255,0.25)', borderRadius: 8, overflow: 'hidden' }}>
          <button type="button" title="Zoom out" onClick={() => setZoom((z) => Math.max(0.2, Math.round((z - 0.1) * 10) / 10))} style={{ width: 30, height: 32, border: 'none', background: 'transparent', color: 'white', cursor: 'pointer', fontSize: 16 }}>−</button>
          <button type="button" title="Fit to screen" onClick={fit} style={{ width: 52, height: 32, border: 'none', borderLeft: '1px solid rgba(255,255,255,0.15)', borderRight: '1px solid rgba(255,255,255,0.15)', background: 'transparent', color: 'white', cursor: 'pointer', fontSize: 12, fontWeight: 600, fontFamily: 'var(--font-body)' }}>{Math.round(zoom * 100)}%</button>
          <button type="button" title="Zoom in" onClick={() => setZoom((z) => Math.min(3, Math.round((z + 0.1) * 10) / 10))} style={{ width: 30, height: 32, border: 'none', background: 'transparent', color: 'white', cursor: 'pointer', fontSize: 16 }}>+</button>
        </div>
        <span style={{ width: 1, height: 22, background: 'rgba(255,255,255,0.15)', flexShrink: 0 }}></span>
        <CertMenuButton dark label="View" width={270}>
          <span style={certEdStyles.label}>Show on the page</span>
          <CertToggle label="Rulers (mm)" checked={showRulers} onChange={setShowRulers} />
          <CertToggle label={'Print-safe area (' + CE.SAFE_MM + ' mm)'} checked={showSafe} onChange={setShowSafe} />
          <CertToggle label="Snap to grid" checked={grid.on} onChange={(v) => setGrid((g) => ({ ...g, on: v }))} />
          {grid.on && <CertSeg value={grid.mm} options={[{ value: 2, label: '2 mm' }, { value: 5, label: '5 mm' }, { value: 10, label: '10 mm' }]} onChange={(v) => setGrid((g) => ({ ...g, mm: v }))} />}
        </CertMenuButton>
        <CertMenuButton dark label={<><span className="ce-short">Preview</span><span className="ce-long">{'Preview: ' + previewLabel}</span></>} width={300} onOpen={openPreview}>
          {(hide) => (<>
            <span style={certEdStyles.label}>Show the certificate with</span>
            <button type="button" className="ce-btn" style={certEdStyles.palBtn} onClick={() => { setPreviewData(null); setPreviewLabel('Sample data'); hide(); }}>Sample data</button>
            <CertField label="A real attendee from">
              <CertSelect value={pvSub} placeholder={mainEvents ? 'Choose a sub-event' : 'Loading…'} onChange={(v) => pickPreviewSub(v)} options={subOptions.map((o) => ({ value: o.s.id, label: o.s.title }))} />
            </CertField>
            {pvSub && <CertField label="Attendee"><CertPreviewAttSelect atts={pvAtts} onPick={(id) => { pickPreviewAtt(id); hide(); }} /></CertField>}
          </>)}
        </CertMenuButton>
        <CertMenuButton dark label="More" width={250}>
          {(hide) => (<>
            <button type="button" className="ce-ctx-item" style={{ display: 'flex', alignItems: 'center', gap: 10, width: '100%', minHeight: 36, padding: '0 10px', border: 'none', borderRadius: 8, background: 'transparent', cursor: 'pointer', fontSize: 13, fontWeight: 500, color: 'var(--navy-900)', fontFamily: 'var(--font-body)', textAlign: 'left' }} onClick={() => { hide(); testPrint(); }}><CertIcon d="M4 6V2h8v4M4 12H2V7h12v5h-2M4 10h8v4H4z" />Test print</button>
            <button type="button" className="ce-ctx-item" style={{ display: 'flex', alignItems: 'center', gap: 10, width: '100%', minHeight: 36, padding: '0 10px', border: 'none', borderRadius: 8, background: 'transparent', cursor: 'pointer', fontSize: 13, fontWeight: 500, color: 'var(--navy-900)', fontFamily: 'var(--font-body)', textAlign: 'left' }} onClick={() => { hide(); exportPdf(); }}><CertIcon d="M8 2v8M5 7l3 3 3-3M3 13h10" />Export as PDF</button>
            <button type="button" className="ce-ctx-item" style={{ display: 'flex', alignItems: 'center', gap: 10, width: '100%', minHeight: 36, padding: '0 10px', border: 'none', borderRadius: 8, background: 'transparent', cursor: 'pointer', fontSize: 13, fontWeight: 500, color: 'var(--navy-900)', fontFamily: 'var(--font-body)', textAlign: 'left' }} onClick={() => { hide(); toggleLayoutLock(); }}><CertIcon d={layoutLocked ? CERT_ICONS.unlock : CERT_ICONS.lock} />{layoutLocked ? 'Unlock layout' : 'Lock layout (wording-only edits)'}</button>
            <div style={{ height: 1, background: 'var(--border-default)', margin: '2px 0' }}></div>
            <button type="button" className="ce-ctx-item" style={{ display: 'flex', alignItems: 'center', gap: 10, width: '100%', minHeight: 36, padding: '0 10px', border: 'none', borderRadius: 8, background: 'transparent', cursor: 'pointer', fontSize: 13, fontWeight: 500, color: 'var(--navy-900)', fontFamily: 'var(--font-body)', textAlign: 'left' }} onClick={() => { hide(); setHelpOpen(true); }}><CertIcon d="M6 6a2 2 0 113 1.7c-.6.4-1 .8-1 1.5M8 11.5v.5" />Keyboard shortcuts<span style={{ marginLeft: 'auto', fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-muted)' }}>?</span></button>
          </>)}
        </CertMenuButton>
        {isNew ? <button type="button" onClick={() => save()} disabled={!!busy} title={versionLabel} style={{ ...certEdStyles.iconBtn, height: 34, flexShrink: 0, whiteSpace: 'nowrap', background: 'var(--brand-primary)', borderColor: 'var(--brand-primary)', color: 'white', fontWeight: 700 }}>Save template</button>
          : <CertSaveWithNote busy={!!busy} onSave={(note) => save(note)} />}
      </div>
      <div style={{ flex: 1, minHeight: 0, display: 'flex' }}>
        <aside style={{ width: 220, flexShrink: 0, background: 'white', borderRight: '1px solid var(--border-default)', overflowY: 'auto', position: 'relative' }}><div style={{ opacity: layoutLocked ? 0.45 : 1, pointerEvents: layoutLocked ? 'none' : 'auto' }}>{palette}</div></aside>
        <div style={{ flex: 1, minWidth: 0, position: 'relative', display: 'flex' }}>
        <div style={{ position: 'absolute', top: 12, left: 12, right: 12, zIndex: 4, display: 'flex', gap: 8, flexWrap: 'wrap', pointerEvents: 'none' }}>
          {layoutLocked && <div style={{ pointerEvents: 'auto', display: 'flex', alignItems: 'center', gap: 10, padding: '6px 6px 6px 12px', borderRadius: 999, background: 'var(--navy-900)', color: 'white', fontSize: 12.5, fontWeight: 600, boxShadow: 'var(--shadow-md)' }}><CertIcon d={CERT_ICONS.lock} />Layout locked: only wording and details can change<button type="button" onClick={toggleLayoutLock} style={{ height: 26, padding: '0 10px', borderRadius: 999, border: 'none', background: 'white', color: 'var(--navy-900)', fontWeight: 700, fontSize: 12, cursor: 'pointer', fontFamily: 'var(--font-body)' }}>Unlock</button></div>}
          {showSafe && unsafe.length > 0 && <button type="button" onClick={() => { setSelIds(unsafe.map((u) => u.id)); setTab('props'); }} title="These may get cut off by the printer" style={{ pointerEvents: 'auto', display: 'flex', alignItems: 'center', gap: 6, height: 32, padding: '0 12px', borderRadius: 999, border: '1px solid #E8B44A', background: '#FFF6E0', color: '#7A4F00', fontSize: 12.5, fontWeight: 600, cursor: 'pointer', boxShadow: 'var(--shadow-sm)', fontFamily: 'var(--font-body)' }}>⚠ {unsafe.length} element{unsafe.length === 1 ? '' : 's'} near the edge · Select</button>}
        </div>
        <main ref={stageRef} onPointerDown={stageDown} onContextMenu={(e) => { e.preventDefault(); if (layoutLockedRef.current) return; setSelIds([]); setCtxMenu({ x: e.clientX, y: e.clientY, empty: true }); }} style={{ flex: 1, minWidth: 0, overflow: 'auto', display: 'flex', padding: 32, position: 'relative' }}>
          <div style={{ margin: 'auto', position: 'relative', width: W * zoom, height: H * zoom, boxShadow: '0 8px 30px rgba(14,34,71,0.18)' + (palGhost && palGhost.over ? ', 0 0 0 3px var(--brand-primary)' : ''), flexShrink: 0, transition: 'box-shadow .15s ease' }}>
            <canvas ref={canvasRef} style={{ width: W * zoom, height: H * zoom, display: 'block' }}></canvas>
            {grid.on && <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', backgroundImage: 'linear-gradient(to right, rgba(14,34,71,.12) 1px, transparent 1px), linear-gradient(to bottom, rgba(14,34,71,.12) 1px, transparent 1px)', backgroundSize: (grid.mm * CE.MM * zoom) + 'px ' + (grid.mm * CE.MM * zoom) + 'px' }}></div>}
            {showSafe && <div style={{ position: 'absolute', left: SAFE * zoom, top: SAFE * zoom, right: SAFE * zoom, bottom: SAFE * zoom, border: '1px dashed rgba(224,64,138,.7)', pointerEvents: 'none' }}></div>}
            {showRulers && <CertRuler len={W} zoom={zoom} axis="x" />}
            {showRulers && <CertRuler len={H} zoom={zoom} axis="y" />}
            <div style={{ position: 'absolute', inset: 0 }}>
              {design.elements.map((el) => el.hidden ? null : (
                <div key={el.id}
                  onPointerDown={(e) => startDrag(e, el.id, 'move')}
                  onContextMenu={(e) => { e.preventDefault(); e.stopPropagation(); if (layoutLockedRef.current) return; if (selIdsRef.current.indexOf(el.id) === -1) setSelIds(el.group ? designRef.current.elements.filter((x) => x.group === el.group && !x.hidden).map((x) => x.id) : [el.id]); setCtxMenu({ x: e.clientX, y: e.clientY }); }}
                  onDoubleClick={() => { if (el.type === 'text') { setTab('props'); setTimeout(() => textRef.current && textRef.current.focus(), 30); } }}
                  style={{ position: 'absolute', left: el.x * zoom, top: el.y * zoom, width: el.w * zoom, height: el.h * zoom, cursor: el.locked || layoutLocked ? 'default' : 'move', transform: el.rotation ? 'rotate(' + el.rotation + 'deg)' : undefined, outline: selIds.indexOf(el.id) !== -1 ? (multi ? '1.5px dashed var(--brand-primary)' : '1.5px solid var(--brand-primary)') : 'none', outlineOffset: 0 }}
                  className="ud-cert-hit">
                  {el.id === selId && !el.locked && !layoutLocked && (
                    <>
                      <div style={{ position: 'absolute', left: '50%', top: -26, width: 0, height: 26, borderLeft: '1px solid var(--brand-primary)', pointerEvents: 'none' }}></div>
                      <div title="Drag to rotate (Shift snaps to 15°)" onPointerDown={(e) => startRotate(e, el.id)} style={{ position: 'absolute', left: '50%', top: -34, width: 14, height: 14, marginLeft: -7, borderRadius: '50%', background: 'white', border: '1.5px solid var(--brand-primary)', cursor: 'grab', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><svg width="8" height="8" viewBox="0 0 10 10"><path d="M8 5a3 3 0 11-1-2.2M8 1v2H6" fill="none" stroke="#F49B52" strokeWidth="1.4" strokeLinecap="round" /></svg></div>
                    </>
                  )}
                  {el.id === selId && !el.locked && !layoutLocked && CERT_HANDLES.map((h) => (
                    <div key={h} onPointerDown={(e) => startDrag(e, el.id, 'resize', h)} style={{ position: 'absolute', left: certHandlePos[h][0] * 100 + '%', top: certHandlePos[h][1] * 100 + '%', width: 9, height: 9, marginLeft: -4.5, marginTop: -4.5, background: 'white', border: '1.5px solid var(--brand-primary)', borderRadius: 2, cursor: certHandleCursor[h] }}></div>
                  ))}
                  {el.id === selId && el.locked && <span style={{ position: 'absolute', top: -20, left: 0, fontSize: 10, background: 'var(--navy-900)', color: 'white', padding: '2px 6px', borderRadius: 3 }}>Locked</span>}
                </div>
              ))}
              {multi && selEls.length > 1 && (() => { const b = selBox(selEls); return (
                <div style={{ position: 'absolute', left: b.x * zoom - 4, top: b.y * zoom - 4, width: b.w * zoom + 8, height: b.h * zoom + 8, border: '1.5px solid var(--brand-primary)', borderRadius: 3, pointerEvents: 'none' }}>
                  {!layoutLocked && CERT_HANDLES.map((h) => <div key={h} onPointerDown={(e) => startGroupResize(e, h)} style={{ position: 'absolute', left: certHandlePos[h][0] * 100 + '%', top: certHandlePos[h][1] * 100 + '%', width: 10, height: 10, marginLeft: -5, marginTop: -5, background: 'var(--brand-primary)', border: '1.5px solid white', borderRadius: 2, cursor: certHandleCursor[h], pointerEvents: 'auto' }}></div>)}
                </div>); })()}
              {marquee && <div style={{ position: 'absolute', left: marquee.x * zoom, top: marquee.y * zoom, width: marquee.w * zoom, height: marquee.h * zoom, border: '1px dashed var(--brand-primary)', background: 'color-mix(in srgb, var(--brand-primary) 10%, transparent)', pointerEvents: 'none' }}></div>}
              {guides.filter((g) => g.gap && g.b - g.a > 0.5).map((g, i) => {
                const len = (g.b - g.a) * zoom, mm = Math.round((g.b - g.a) / CE.MM * 10) / 10, col = g.eq ? '#E0408A' : '#7A8699';
                const lbl = <span style={{ position: 'absolute', left: '50%', top: '50%', transform: 'translate(-50%,-50%)', background: col, color: 'white', fontSize: 10, fontWeight: 700, padding: '1px 5px', borderRadius: 4, whiteSpace: 'nowrap', fontFamily: 'var(--font-body)' }}>{mm} mm{g.eq ? ' =' : ''}</span>;
                return g.axis === 'h'
                  ? <div key={'gap' + i} style={{ position: 'absolute', left: g.a * zoom, top: g.at * zoom, width: len, height: 0, borderTop: '1px solid ' + col, pointerEvents: 'none' }}>{len > 26 && lbl}</div>
                  : <div key={'gap' + i} style={{ position: 'absolute', top: g.a * zoom, left: g.at * zoom, height: len, width: 0, borderLeft: '1px solid ' + col, pointerEvents: 'none' }}>{len > 18 && lbl}</div>;
              })}
              {guides.filter((g) => !g.gap).map((g, i) => (
                <div key={i} style={g.v
                  ? { position: 'absolute', left: g.pos * zoom, top: 0, bottom: 0, width: 0, borderLeft: '1px ' + (g.center ? 'solid' : 'dashed') + ' #E0408A', pointerEvents: 'none' }
                  : { position: 'absolute', top: g.pos * zoom, left: 0, right: 0, height: 0, borderTop: '1px ' + (g.center ? 'solid' : 'dashed') + ' #E0408A', pointerEvents: 'none' }}></div>
              ))}
            </div>
          </div>
        </main>
        </div>
        <aside style={{ width: 300, flexShrink: 0, background: 'white', borderLeft: '1px solid var(--border-default)', display: 'flex', flexDirection: 'column', minHeight: 0 }}>
          <div style={{ display: 'flex', borderBottom: '1px solid var(--border-default)' }}>
            {[{ v: 'props', l: multi ? selIds.length + ' selected' : sel ? 'Element' : 'Page' }, { v: 'layers', l: 'Layers (' + design.elements.length + ')' }].map((t) => (
              <button key={t.v} type="button" onClick={() => setTab(t.v)} style={{ flex: 1, padding: '12px 8px', border: 'none', borderBottom: tab === t.v ? '2px solid var(--brand-primary)' : '2px solid transparent', background: 'white', fontWeight: tab === t.v ? 700 : 500, fontSize: 13, cursor: 'pointer', color: 'var(--text-primary)', fontFamily: 'var(--font-body)' }}>{t.l}</button>
            ))}
          </div>
          <div key={tab} className="ud-tab-panel" style={{ flex: 1, overflowY: 'auto' }}>{tab === 'layers' ? layersPanel : (multi ? multiPanel : sel ? (layoutLocked ? lockedElPanel : elPanel) : pagePanel)}</div>
        </aside>
      </div>

      {libOpen && ReactDOM.createPortal(
        <div data-ce-portal="1" className="ce-pop" style={{ position: 'fixed', left: 232, top: 120, width: 320, maxHeight: 'calc(100vh - 140px)', overflowY: 'auto', zIndex: 2100, background: 'white', border: '1px solid var(--border-default)', borderRadius: 12, boxShadow: '0 16px 36px rgba(5,13,26,.24)', padding: 14, fontFamily: 'var(--font-body)', transformOrigin: 'top left' }}>
          <div style={{ display: 'flex', alignItems: 'center', marginBottom: 10 }}>
            <div style={{ fontWeight: 700, fontSize: 14, flex: 1 }}>Saved images</div>
            <button type="button" aria-label="Close" onClick={() => setLibOpen(false)} style={{ width: 28, height: 28, borderRadius: '50%', border: 'none', background: 'var(--bg-sunken)', cursor: 'pointer', fontSize: 16 }}>×</button>
          </div>
          {libItems.length > 0 && (
            <div style={{ position: 'relative', marginBottom: 10 }}>
              <svg width="14" height="14" viewBox="0 0 16 16" style={{ position: 'absolute', left: 10, top: 11, color: 'var(--text-muted)' }}><circle cx="7" cy="7" r="4.5" fill="none" stroke="currentColor" strokeWidth="1.6" /><path d="M10.5 10.5L14 14" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" /></svg>
              <input autoFocus value={libQ} onChange={(ev) => setLibQ(ev.target.value)} placeholder="Search saved images" style={{ width: '100%', height: 36, boxSizing: 'border-box', padding: '0 30px 0 32px', borderRadius: 8, border: '1.5px solid var(--border-default)', fontSize: 13, fontFamily: 'var(--font-body)', outline: 'none' }} />
              {libQ && <button type="button" aria-label="Clear search" onClick={() => setLibQ('')} style={{ position: 'absolute', right: 6, top: 7, width: 22, height: 22, borderRadius: '50%', border: 'none', background: 'var(--bg-sunken)', cursor: 'pointer', fontSize: 13, lineHeight: '20px', padding: 0 }}>×</button>}
            </div>
          )}
          {libItems.length > 0 && <div style={{ display: 'flex', gap: 6, marginBottom: 10 }}>{[['all', 'All'], ['image', 'Images'], ['signature', 'Signatures']].map(([k, l]) => <button key={k} type="button" className="ce-pill" onClick={() => setLibKind(k)} style={{ height: 26, padding: '0 10px', borderRadius: 999, border: '1.5px solid ' + (libKind === k ? 'var(--navy-900)' : 'var(--border-default)'), background: libKind === k ? 'var(--navy-900)' : 'white', color: libKind === k ? 'white' : 'var(--navy-900)', fontSize: 11.5, fontWeight: 600, cursor: 'pointer', fontFamily: 'var(--font-body)' }}>{l}</button>)}</div>}
          {libItems.length === 0 ? <div style={{ fontSize: 12.5, color: 'var(--text-muted)', lineHeight: 1.5 }}>Logos and signatures you upload are saved here, so you can reuse them in any template without uploading again.</div> : libShown.length === 0 ? <div style={{ fontSize: 12.5, color: 'var(--text-muted)', padding: '6px 0' }}>No saved images match.</div> : (
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
              {libShown.map((it) => (
                <div key={it.id} style={{ position: 'relative' }}>
                  <button type="button" title={'Add ' + it.name} onClick={async () => { const src = CE.srcOf(it.id); const img = new Image(); img.src = src; await img.decode().catch(() => {}); const r = img.naturalWidth && img.naturalHeight ? img.naturalWidth / img.naturalHeight : 2; const w = it.kind === 'signature' ? 180 : 160; addEl({ id: CE.uid(), type: 'image', name: it.kind === 'signature' ? 'Signature' : it.name, src: it.id, fit: 'contain', w, h: Math.round(w / r), opacity: 1, x: null, y: null }); setLibOpen(false); }} className="ce-btn" style={{ width: '100%', aspectRatio: '1', padding: 6, border: '1.5px solid var(--border-default)', borderRadius: 8, background: 'repeating-conic-gradient(#f2f2f2 0 25%, #fff 0 50%) 0 0/12px 12px', cursor: 'pointer' }}><img src={CE.srcOf(it.id)} alt={it.name} style={{ width: '100%', height: '100%', objectFit: 'contain' }} /></button>
                  <button type="button" title="Remove from saved images" onClick={() => { CE.removeFromLibrary(it.id); setLibItems(CE.loadLibrary()); }} style={{ position: 'absolute', top: -6, right: -6, width: 20, height: 20, borderRadius: '50%', border: '1.5px solid white', background: 'var(--navy-900)', color: 'white', fontSize: 12, lineHeight: '16px', cursor: 'pointer', padding: 0 }}>×</button>
                  <div style={{ fontSize: 10.5, color: 'var(--text-muted)', marginTop: 3, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{it.kind === 'signature' ? 'Signature' : it.name}</div>
                </div>
              ))}
            </div>
          )}
        </div>, document.body)}
      {cropFor && (() => { const ce = design.elements.find((x) => x.id === cropFor); return ce ? <CertCropDialog el={ce} onClose={() => setCropFor(null)} onApply={(cr) => { updateEl(ce.id, { crop: cr }); setCropFor(null); }} /> : null; })()}
      {helpOpen && <CertHelpDialog onClose={() => setHelpOpen(false)} />}
      {sigPad && <CertSignaturePad onClose={() => setSigPad(null)} onSave={(url, r) => { const id = CE.putAsset(url); CE.addToLibrary(id, 'signature', 'Drawn signature'); setLibItems(CE.loadLibrary()); const w = 180, h = Math.round(w / r), pt = sigPad.pt; addEl({ id: CE.uid(), type: 'image', name: 'Signature', src: id, fit: 'contain', w, h, opacity: 1, x: pt ? pt.x - w / 2 : null, y: pt ? pt.y - h / 2 : null }); setSigPad(null); }} />}
      {ctxMenu && <CertCtxMenu menu={ctxMenu} onClose={() => setCtxMenu(null)} count={selIds.length} locked={selEls.length > 0 && selEls.every((x) => x.locked)}
        act={(a) => { setCtxMenu(null);
          if (a === 'dup') duplicateSel(); else if (a === 'del') removeSel(); else if (a === 'front' || a === 'back' || a === 'forward' || a === 'backward') reorderSel(a);
          else if (a === 'lock') patchSel({ locked: true }); else if (a === 'unlock') patchSel({ locked: false }); else if (a === 'hide') { patchSel({ hidden: true }); setSelIds([]); }
          else if (a === 'all') { setSelIds(designRef.current.elements.filter((x) => !x.hidden && !x.locked).map((x) => x.id)); setTab('props'); }
          else if (a === 'grid') setGrid((g) => ({ ...g, on: !g.on })); else if (a === 'rulers') setShowRulers((v) => !v); else if (a.indexOf('al-') === 0) alignSel(a.slice(3));
          else if (a === 'props') setTab('props'); else if (a === 'copy') copySel(); else if (a === 'paste') pasteClip(); else if (a === 'copystyle') copyStyle(); else if (a === 'pastestyle') pasteStyle(); else if (a === 'group') groupSel(); else if (a === 'ungroup') ungroupSel(); }}
        gridOn={grid.on} rulersOn={showRulers} grouped={selEls.length > 1 && selEls.every((x) => x.group && x.group === selEls[0].group)} />}
      {busy && <div style={{ position: 'fixed', bottom: 24, left: '50%', transform: 'translateX(-50%)', background: 'var(--navy-950)', color: 'white', padding: '10px 18px', borderRadius: 8, fontSize: 13, display: 'flex', alignItems: 'center', gap: 10, boxShadow: 'var(--shadow-lg)' }}><span className="ud-spinner"></span>{busy}</div>}
      {toast && <div onClick={() => setToast(null)} style={{ position: 'fixed', bottom: 24, right: 24, background: toast.isError ? 'var(--status-error)' : 'var(--status-success)', color: 'white', padding: '10px 16px', borderRadius: 8, fontSize: 13, boxShadow: 'var(--shadow-lg)', cursor: 'pointer', maxWidth: 380 }}>{toast.msg}</div>}
    </div>,
    document.body
  );
}

window.CertEditor = CertEditor;
Object.assign(window, { CertSelect, CertCheck, CertNum, CertSlider, CertPresence, CertLeaveCtx });
