// Company Logo — upload, smart crop engine, thumbnails, loading experience
(function injectLogoStyles() {
  if (typeof document === 'undefined') return;
  const prev = document.getElementById('om-logo-styles');
  if (prev) prev.remove();
  const el = document.createElement('style');
  el.id = 'om-logo-styles';
  el.textContent = `
    @keyframes omLogoBreathe { 0%,100%{transform:scale(.98);opacity:.85} 50%{transform:scale(1);opacity:1} }
    @keyframes omLogoRing { to { transform:rotate(360deg) } }
    @keyframes omLogoFadeIn { from{opacity:0;transform:scale(.96)} to{opacity:1;transform:scale(1)} }
    @keyframes omLogoFadeOut { from{opacity:1;transform:scale(1)} to{opacity:0;transform:scale(.97)} }
    .om-lg-ov{position:absolute;inset:0;background:rgba(255,255,255,.86);backdrop-filter:blur(14px);-webkit-backdrop-filter:blur(14px);display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;z-index:30;border-radius:inherit;animation:omLogoFadeIn .35s cubic-bezier(.2,.8,.2,1)}
    .om-lg-ov.leaving{animation:omLogoFadeOut .3s cubic-bezier(.4,0,1,1) forwards}
    .om-lg-ring{position:absolute;width:88px;height:88px;border-radius:50%;border:2px solid transparent;border-top-color:var(--or,#EA580C);border-right-color:var(--or,#EA580C);animation:omLogoRing 1.1s linear infinite;opacity:.55}
    .om-lg-mark{width:56px;height:56px;object-fit:contain;animation:omLogoBreathe 2.1s ease-in-out infinite;position:relative;z-index:1;filter:drop-shadow(0 2px 10px rgba(0,0,0,.08))}
    .om-lg-status{font-size:11.5px;color:var(--txt2,#6B7280);font-weight:600;letter-spacing:.01em}
    .om-lg-canvas{position:relative;overflow:hidden;background:repeating-conic-gradient(#f3f4f6 0% 25%,#fafafa 0% 50%) 50%/16px 16px;touch-action:none;cursor:grab;user-select:none;border-radius:16px;border:1px solid var(--bdr,#E5E7EB);width:100%;max-width:560px;aspect-ratio:1/1;margin:0 auto}
    .om-lg-canvas:active{cursor:grabbing}
    .om-lg-btn{display:inline-flex;align-items:center;justify-content:center;gap:5px;border:1px solid var(--bdr,#E5E7EB);background:#fff;border-radius:8px;padding:7px 12px;font-size:11.5px;font-weight:600;color:var(--txt,#111827);cursor:pointer;transition:all .15s ease}
    .om-lg-btn:hover{background:#F9FAFB;border-color:#D1D5DB}
    .om-lg-btn:focus-visible{outline:2px solid var(--or,#EA580C);outline-offset:2px}
    .om-lg-btn.active{background:var(--or-lt,#FFF7ED);border-color:var(--or,#EA580C);color:var(--or,#EA580C)}
    .om-lg-icon-btn{width:32px;height:32px;border-radius:8px;border:1px solid var(--bdr,#E5E7EB);background:#fff;display:flex;align-items:center;justify-content:center;cursor:pointer;transition:all .15s ease;color:var(--txt,#111827);font-size:16px;line-height:1}
    .om-lg-icon-btn:hover{background:#F9FAFB;border-color:#D1D5DB}
    .om-lg-icon-btn:focus-visible{outline:2px solid var(--or,#EA580C);outline-offset:2px}
    .om-lg-ratio{padding:5px 10px;font-size:11px}
    .om-lg-handle{position:absolute;background:#fff;border:2px solid var(--or,#EA580C);border-radius:3px;box-shadow:0 1px 4px rgba(0,0,0,.25);z-index:5}
    .om-lg-handle.edge{background:var(--or,#EA580C);opacity:.9}
    .om-lg-mask{position:absolute;pointer-events:none;box-shadow:0 0 0 2000px rgba(0,0,0,.35);border:1.5px solid rgba(255,255,255,.9);z-index:2}
    .om-lg-ratio-row{display:flex;gap:5px;justify-content:center;flex-wrap:wrap;width:100%}
    .om-lg-ctrl-row{display:flex;gap:10px;flex-wrap:wrap;justify-content:center;width:100%}
    .om-lg-ctrl-group{display:flex;gap:6px;align-items:center;justify-content:center;flex-wrap:wrap}
    @media(max-width:768px){
      .om-lg-ratio-row{flex-wrap:nowrap;overflow-x:auto;-webkit-overflow-scrolling:touch;scroll-snap-type:x proximity;justify-content:flex-start;padding:3px 2px 8px;margin:0 -2px;scrollbar-width:none}
      .om-lg-ratio-row::-webkit-scrollbar{display:none}
      .om-lg-ratio-row .om-lg-btn{flex:0 0 auto;scroll-snap-align:start;min-height:44px;padding:0 16px}
      .om-lg-ctrl-row{flex-direction:column;align-items:stretch;gap:8px}
      .om-lg-ctrl-group{width:100%}
      .om-lg-icon-btn{width:44px;height:44px;flex-shrink:0}
      .om-lg-ctrl-group input[type=range]{flex:1;width:auto!important}
      .om-lg-canvas{max-width:100%}
    }
    @media(max-width:768px) and (orientation:landscape){
      .om-lg-canvas{width:min(58vh,58vw);max-width:min(58vh,58vw)}
    }
  `;
  document.head.appendChild(el);
})();

const { useState: _lgSt, useEffect: _lgFx, useRef: _lgRf } = React;

const OM_GROUP_MARK = 'uploads/OM GROUP ONLY LOGO-9de09387.png';
const ACCEPTED_TYPES = ['image/png', 'image/svg+xml', 'image/jpeg', 'image/webp'];
const MAX_SIZE = 5 * 1024 * 1024; // 5MB
const RATIOS = [ ['orig','Original',null], ['free','Freeform',null], ['1:1','1:1',1], ['4:3','4:3',4/3], ['3:4','3:4',3/4], ['16:9','16:9',16/9], ['9:16','9:16',9/16], ['circle','Circle',1] ];

function LogoFallbackIcon({ size = 32, isGroup }) {
  if (isGroup) return <img src={OM_GROUP_MARK} alt="OM Group" style={{ width: size, height: size, objectFit: 'contain', flexShrink: 0 }} />;
  return (
    <svg width={size * 0.65} height={size * 0.65} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ flexShrink: 0 }}>
      <path d="M3 21h18M9 8h1m-1 4h1m4-4h1m-1 4h1M5 21V5a2 2 0 012-2h10a2 2 0 012 2v16" />
    </svg>
  );
}

function CompanyLogoThumb({ logo, isGroup, size = 32, radius = 8 }) {
  if (logo) return <img src={logo} alt="" style={{ width: size, height: size, objectFit: 'contain', flexShrink: 0, background: 'transparent' }} />;
  if (isGroup) return <LogoFallbackIcon size={size} isGroup />;
  return null;
}

function LogoLoadingOverlay({ status, leaving }) {
  return (
    <div className={`om-lg-ov${leaving ? ' leaving' : ''}`} role="status" aria-live="polite">
      <div style={{ position: 'relative', width: 88, height: 88, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div className="om-lg-ring" />
        <img className="om-lg-mark" src={OM_GROUP_MARK} alt="" />
      </div>
      <div className="om-lg-status">{status}</div>
    </div>
  );
}

// ── Interactive crop editor ──────────────────────────────────────────────
function LogoCropEditor({ file, onCancel, onSave }) {
  const [stage, setStage] = _lgSt('loading');
  const [leaving, setLeaving] = _lgSt(false);
  const [status, setStatus] = _lgSt('Preparing logo…');
  const [img, setImg] = _lgSt(null);
  const [err, setErr] = _lgSt(null);

  const CANVAS = 520; // logical square canvas size; scales responsively via CSS
  const [ratio, setRatio] = _lgSt('1:1');
  const [tx, setTx] = _lgSt(0);
  const [ty, setTy] = _lgSt(0);
  const [scale, setScale] = _lgSt(1);
  const [minScale, setMinScale] = _lgSt(0.05);
  const [rot, setRot] = _lgSt(0);
  const [rect, setRect] = _lgSt({ x: 60, y: 60, w: 400, h: 400 });

  const drag = _lgRf(null);
  const pinch = _lgRf(null);
  const resizeDrag = _lgRf(null);
  const canvasRef = _lgRf(null);
  const trapRef = _lgRf(null);

  function rectForRatio(r, prevRect) {
    const aspect = RATIOS.find(x => x[0] === r);
    const cx = prevRect ? prevRect.x + prevRect.w / 2 : CANVAS / 2;
    const cy = prevRect ? prevRect.y + prevRect.h / 2 : CANVAS / 2;
    let w, h;
    if (r === 'free') { w = prevRect ? prevRect.w : CANVAS * 0.7; h = prevRect ? prevRect.h : CANVAS * 0.7; }
    else if (r === 'orig' && img) { const a = img.width / img.height; w = CANVAS * 0.8; h = w / a; if (h > CANVAS * 0.8) { h = CANVAS * 0.8; w = h * a; } }
    else { const a = aspect[2] || 1; w = CANVAS * 0.8; h = w / a; if (h > CANVAS * 0.8) { h = CANVAS * 0.8; w = h * a; } }
    let x = cx - w / 2, y = cy - h / 2;
    x = Math.max(0, Math.min(CANVAS - w, x));
    y = Math.max(0, Math.min(CANVAS - h, y));
    return { x, y, w, h };
  }

  // Load image, fit ENTIRE image into view before any interaction
  _lgFx(() => {
    let cancelled = false;
    setStatus('Uploading logo…');
    const reader = new FileReader();
    reader.onload = () => {
      if (cancelled) return;
      setStatus('Preparing logo…');
      const image = new Image();
      image.onload = () => {
        if (cancelled) return;
        const fit = Math.min(CANVAS / image.width, CANVAS / image.height) * 0.94;
        setImg(image);
        setMinScale(fit * 0.3);
        setScale(fit);
        setTx(0); setTy(0); setRot(0);
        setRect(rectForRatio('1:1'));
        setStatus('Optimizing image…');
        requestAnimationFrame(() => { if (!cancelled) setStage('edit'); });
      };
      image.onerror = () => !cancelled && setErr('Could not read this image. Please try another file.');
      image.src = reader.result;
    };
    reader.onerror = () => !cancelled && setErr('Upload failed. Please try again.');
    reader.readAsDataURL(file);
    return () => { cancelled = true; };
  }, [file]);

  _lgFx(() => { trapRef.current && trapRef.current.focus(); }, [stage]);

  // Lock page scroll behind this modal while it's open (crop modal must have full priority)
  _lgFx(() => {
    const prevOverflow = document.body.style.overflow;
    const prevTouch = document.body.style.touchAction;
    document.body.style.overflow = 'hidden';
    document.body.style.touchAction = 'none';
    return () => { document.body.style.overflow = prevOverflow; document.body.style.touchAction = prevTouch; };
  }, []);

  function clampScale(s) { return Math.min(minScale * 20, Math.max(minScale, s)); }
  function zoomBy(factor) { setScale(s => clampScale(s * factor)); }

  function pickRatio(r) {
    setRatio(r);
    setRect(prev => rectForRatio(r, prev));
  }

  function onWheel(e) { e.preventDefault(); zoomBy(e.deltaY < 0 ? 1.08 : 0.93); }

  function onImgPointerDown(e) {
    if (e.touches && e.touches.length === 2) {
      const [a, b] = e.touches;
      pinch.current = { dist: Math.hypot(a.clientX - b.clientX, a.clientY - b.clientY), scale };
      return;
    }
    const p = e.touches ? e.touches[0] : e;
    drag.current = { x: p.clientX, y: p.clientY, tx, ty };
  }
  function onImgPointerMove(e) {
    if (e.touches && e.touches.length === 2 && pinch.current) {
      e.preventDefault();
      const [a, b] = e.touches;
      const d = Math.hypot(a.clientX - b.clientX, a.clientY - b.clientY);
      setScale(clampScale(pinch.current.scale * (d / pinch.current.dist)));
      return;
    }
    if (!drag.current) return;
    const p = e.touches ? e.touches[0] : e;
    const box = canvasRef.current.getBoundingClientRect();
    const f = CANVAS / box.width;
    setTx(drag.current.tx + (p.clientX - drag.current.x) * f);
    setTy(drag.current.ty + (p.clientY - drag.current.y) * f);
  }
  function onImgPointerUp() { drag.current = null; pinch.current = null; }

  function reset() {
    if (!img) return;
    const fit = Math.min(CANVAS / img.width, CANVAS / img.height) * 0.94;
    setScale(fit); setTx(0); setTy(0); setRot(0); setRatio('1:1'); setRect(rectForRatio('1:1'));
  }
  function recenter() { setTx(0); setTy(0); }
  function fitToFrame() { if (img) setScale(Math.min(CANVAS / img.width, CANVAS / img.height) * 0.94); }
  function rotate() { setRot(r => (r + 90) % 360); }
  const [original, setOriginal] = _lgSt(false);

  // ── Crop rect handle dragging ──
  function startHandleDrag(id, e) {
    e.preventDefault(); e.stopPropagation();
    const p = e.touches ? e.touches[0] : e;
    resizeDrag.current = { id, startX: p.clientX, startY: p.clientY, rect0: { ...rect }, box: canvasRef.current.getBoundingClientRect() };
    function move(ev) {
      const rd = resizeDrag.current; if (!rd) return;
      const pp = ev.touches ? ev.touches[0] : ev;
      const f = CANVAS / rd.box.width;
      let dx = (pp.clientX - rd.startX) * f, dy = (pp.clientY - rd.startY) * f;
      let { x, y, w, h } = rd.rect0;
      let left = x, top = y, right = x + w, bottom = y + h;
      const hasE = rd.id.includes('e'), hasW = rd.id.includes('w'), hasN = rd.id.includes('n'), hasS = rd.id.includes('s');
      if (hasE) right = right + dx;
      if (hasW) left = left + dx;
      if (hasS) bottom = bottom + dy;
      if (hasN) top = top + dy;
      let newW = right - left, newH = bottom - top;
      const MIN = 50;
      if (newW < MIN) { if (hasW) left = right - MIN; else right = left + MIN; newW = MIN; }
      if (newH < MIN) { if (hasN) top = bottom - MIN; else bottom = top + MIN; newH = MIN; }
      const lockedAspect = ratio !== 'free' ? (RATIOS.find(r => r[0] === ratio)[2] || (ratio === 'orig' && img ? img.width / img.height : 1)) : null;
      if (lockedAspect) {
        const wChangeRatio = Math.abs(newW - rd.rect0.w) / rd.rect0.w;
        const hChangeRatio = Math.abs(newH - rd.rect0.h) / rd.rect0.h;
        if (hasE || hasW) {
          if (!(hasN || hasS) || wChangeRatio >= hChangeRatio) { newH = newW / lockedAspect; } else { newW = newH * lockedAspect; }
        } else { newW = newH * lockedAspect; }
        if (hasW) left = right - newW; else right = left + newW;
        if (hasN) top = bottom - newH; else bottom = top + newH;
        if (!hasE && !hasW) { const cx = (left + right) / 2; left = cx - newW / 2; right = cx + newW / 2; }
        if (!hasN && !hasS) { const cy = (top + bottom) / 2; top = cy - newH / 2; bottom = cy + newH / 2; }
      }
      left = Math.max(0, left); top = Math.max(0, top);
      right = Math.min(CANVAS, right); bottom = Math.min(CANVAS, bottom);
      setRect({ x: left, y: top, w: right - left, h: bottom - top });
    }
    function up() { resizeDrag.current = null; window.removeEventListener('mousemove', move); window.removeEventListener('mouseup', up); window.removeEventListener('touchmove', move); window.removeEventListener('touchend', up); }
    window.addEventListener('mousemove', move); window.addEventListener('mouseup', up);
    window.addEventListener('touchmove', move, { passive: false }); window.addEventListener('touchend', up);
  }

  function handleKeyDown(e) {
    if (e.key === 'Escape') { onCancel(); return; }
    const step = e.shiftKey ? 20 : 6;
    if (e.key === 'ArrowLeft') { setTx(v => v - step); e.preventDefault(); }
    if (e.key === 'ArrowRight') { setTx(v => v + step); e.preventDefault(); }
    if (e.key === 'ArrowUp') { setTy(v => v - step); e.preventDefault(); }
    if (e.key === 'ArrowDown') { setTy(v => v + step); e.preventDefault(); }
    if (e.key === '+' || e.key === '=') { zoomBy(1.1); e.preventDefault(); }
    if (e.key === '-') { zoomBy(0.9); e.preventDefault(); }
  }

  function renderScene(ctx, size) {
    const f = size / CANVAS;
    ctx.save();
    ctx.translate(size / 2, size / 2);
    ctx.translate(tx * f, ty * f);
    ctx.rotate((rot * Math.PI) / 180);
    ctx.scale(scale * f, scale * f);
    ctx.drawImage(img, -img.width / 2, -img.height / 2);
    ctx.restore();
  }

  function doSave() {
    const SS = 3;
    const sceneSize = CANVAS * SS;
    const scene = document.createElement('canvas');
    scene.width = sceneSize; scene.height = sceneSize;
    // Explicitly use alpha:true so transparency is never lost
    const sctx = scene.getContext('2d', { alpha: true });
    sctx.clearRect(0, 0, sceneSize, sceneSize);
    renderScene(sctx, sceneSize);
    const sx = Math.round(rect.x * SS), sy = Math.round(rect.y * SS);
    const sw = Math.round(rect.w * SS), sh = Math.round(rect.h * SS);
    const LONG = 640;
    const outScale = Math.min(1, LONG / Math.max(sw, sh));
    const out = document.createElement('canvas');
    out.width = Math.round(sw * outScale); out.height = Math.round(sh * outScale);
    const octx = out.getContext('2d', { alpha: true });
    // Start fully transparent — never paint a white fill
    octx.clearRect(0, 0, out.width, out.height);
    if (ratio === 'circle') {
      octx.save();
      octx.beginPath();
      octx.arc(out.width / 2, out.height / 2, Math.min(out.width, out.height) / 2, 0, Math.PI * 2);
      octx.clip();
    }
    octx.drawImage(scene, sx, sy, sw, sh, 0, 0, out.width, out.height);
    if (ratio === 'circle') octx.restore();
    setLeaving(true);
    // Always export as PNG to preserve alpha channel
    setTimeout(() => onSave(out.toDataURL('image/png')), 260);
  }

  const handles = [
    ['nw', 'nwse-resize'], ['n', 'ns-resize'], ['ne', 'nesw-resize'],
    ['w', 'ew-resize'], ['e', 'ew-resize'],
    ['sw', 'nesw-resize'], ['s', 'ns-resize'], ['se', 'nwse-resize'],
  ];
  function handleStyle(id) {
    const base = { position: 'absolute', zIndex: 5 };
    const corner = id.length === 2;
    const size = corner ? 14 : 10;
    const cx = rect.x + rect.w / 2, cy = rect.y + rect.h / 2;
    let left, top;
    if (id.includes('w')) left = rect.x; else if (id.includes('e')) left = rect.x + rect.w; else left = cx;
    if (id.includes('n')) top = rect.y; else if (id.includes('s')) top = rect.y + rect.h; else top = cy;
    const pct = 100 / CANVAS;
    return { ...base, left: `${left * pct}%`, top: `${top * pct}%`, width: size, height: size, transform: 'translate(-50%,-50%)', cursor: handles.find(h => h[0] === id)[1] };
  }

  return (
    <div className="mbg" style={{ zIndex: 1200 }} onKeyDown={handleKeyDown} role="dialog" aria-modal="true" aria-label="Edit company logo">
      <div className="mod" style={{ maxWidth: 640, width: '94vw', position: 'relative', maxHeight: '92vh' }} ref={trapRef} tabIndex={-1}>
        <div className="mod-hd">
          <h2>Edit Company Logo</h2>
          <button type="button" className="mod-x" onClick={onCancel} aria-label="Close">×</button>
        </div>
        <div className="mod-bd" style={{ display: 'flex', flexDirection: 'column', gap: 14, alignItems: 'center', position: 'relative', minHeight: stage === 'loading' ? 340 : 'auto' }}>
          {err && (
            <div style={{ width: '100%', background: '#FEF2F2', border: '1px solid #FECACA', borderRadius: 6, padding: '10px 12px', fontSize: 12, color: '#991B1B', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 10 }}>
              <span>{err}</span>
              <button type="button" className="om-lg-btn" onClick={onCancel}>OK</button>
            </div>
          )}
          {!err && stage === 'loading' && <LogoLoadingOverlay status={status} />}
          {!err && stage === 'edit' && img && (
            <>
              <div className="om-lg-ratio-row">
                {RATIOS.map(([id, label]) => (
                  <button key={id} type="button" className={`om-lg-btn om-lg-ratio${ratio === id ? ' active' : ''}`} onClick={() => pickRatio(id)}>{label}</button>
                ))}
              </div>
              <div
                ref={canvasRef}
                className="om-lg-canvas"
                onWheel={onWheel}
                onMouseDown={onImgPointerDown} onMouseMove={onImgPointerMove} onMouseUp={onImgPointerUp} onMouseLeave={onImgPointerUp}
                onTouchStart={onImgPointerDown} onTouchMove={onImgPointerMove} onTouchEnd={onImgPointerUp}
                onDoubleClick={() => setScale(s => (s > minScale * 3 ? minScale : minScale * 3.2))}
                tabIndex={0}
                role="slider" aria-label="Pan and zoom logo" aria-valuenow={Math.round((scale / minScale) * 100)}
              >
                <img
                  src={img.src} alt="" draggable={false}
                  style={{
                    position: 'absolute', left: '50%', top: '50%', pointerEvents: 'none',
                    width: img.width, height: img.height,
                    transform: `translate(-50%,-50%) translate(${tx}px,${ty}px) rotate(${rot}deg) scale(${scale})`,
                    transition: drag.current ? 'none' : 'transform .06s linear',
                  }}
                />
                {!original && (
                  <div className="om-lg-mask" style={{
                    left: `${(rect.x / CANVAS) * 100}%`, top: `${(rect.y / CANVAS) * 100}%`,
                    width: `${(rect.w / CANVAS) * 100}%`, height: `${(rect.h / CANVAS) * 100}%`,
                    borderRadius: ratio === 'circle' ? '50%' : 4,
                  }} />
                )}
                {!original && handles.map(([id]) => (
                  <div key={id} className={`om-lg-handle${id.length === 1 ? ' edge' : ''}`} style={handleStyle(id)}
                    onMouseDown={e => startHandleDrag(id, e)} onTouchStart={e => startHandleDrag(id, e)} />
                ))}
              </div>
              <div className="om-lg-ctrl-row">
                <div className="om-lg-ctrl-group">
                  <button type="button" className="om-lg-icon-btn" title="Zoom out" aria-label="Zoom out" onClick={() => zoomBy(0.88)}>−</button>
                  <input type="range" min={minScale} max={minScale * 20} step={0.001} value={scale} onChange={e => setScale(+e.target.value)} style={{ width: 130 }} aria-label="Zoom level" />
                  <button type="button" className="om-lg-icon-btn" title="Zoom in" aria-label="Zoom in" onClick={() => zoomBy(1.14)}>+</button>
                </div>
                <div className="om-lg-ctrl-group">
                  <button type="button" className="om-lg-btn" onClick={rotate}>Rotate</button>
                  <button type="button" className="om-lg-btn" onClick={fitToFrame}>Fit</button>
                  <button type="button" className="om-lg-btn" onClick={recenter}>Recenter</button>
                </div>
                <div className="om-lg-ctrl-group">
                  <button type="button" className={`om-lg-btn${original ? ' active' : ''}`} onClick={() => setOriginal(o => !o)}>Original View</button>
                  <button type="button" className="om-lg-btn" onClick={reset}>Reset</button>
                </div>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6, alignItems: 'center', width: '100%' }}>
                <div style={{ fontSize: 10.5, color: 'var(--txt2)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '.04em' }}>Live Preview</div>
                <div style={{ display: 'flex', gap: 18, alignItems: 'center' }}>
                  <PreviewChip label="Switcher" size={22} tx={tx} ty={ty} scale={scale} rot={rot} img={img} rect={rect} canvas={CANVAS} circle={ratio === 'circle'} />
                  <PreviewChip label="Header" size={30} tx={tx} ty={ty} scale={scale} rot={rot} img={img} rect={rect} canvas={CANVAS} circle={ratio === 'circle'} />
                </div>
              </div>
            </>
          )}
        </div>
        {!err && stage === 'edit' && (
          <div className="mod-ft">
            <button type="button" className="btn btn-wh" onClick={onCancel}>Cancel</button>
            <button type="button" className="btn btn-or" onClick={doSave}>Save Logo</button>
          </div>
        )}
      </div>
    </div>
  );
}

function PreviewChip({ label, size, tx, ty, scale, rot, img, rect, canvas, circle }) {
  const box = 56;
  const zoom = box / rect.w;
  const offX = box / 2 - ((rect.x + rect.w / 2) - canvas / 2) * zoom;
  const offY = box / 2 - ((rect.y + rect.h / 2) - canvas / 2) * zoom;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 5 }}>
      <div style={{ width: box, height: box, borderRadius: circle ? '50%' : 10, overflow: 'hidden', border: '1px solid var(--bdr)', position: 'relative', background: '#fff' }}>
        <img src={img.src} alt="" style={{
          position: 'absolute', left: offX, top: offY,
          width: img.width * scale * zoom, height: img.height * scale * zoom,
          transform: `translate(-50%,-50%) translate(${tx * zoom}px,${ty * zoom}px) rotate(${rot}deg)`,
        }} />
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 4, fontSize: 10, color: 'var(--txt2)' }}>
        <span style={{ width: size * 0.4, height: size * 0.4, borderRadius: 4, background: '#F3F4F6', display: 'inline-block' }} />
        {label}
      </div>
    </div>
  );
}

// ── Form field: Add/Edit Company modal integration ──
function CompanyLogoField({ value, onChange, onRemove }) {
  const [pending, setPending] = _lgSt(null);
  const [error, setError] = _lgSt(null);
  const inputRef = _lgRf(null);

  function pickFile() { inputRef.current && inputRef.current.click(); }

  function handleFile(e) {
    const file = e.target.files && e.target.files[0];
    e.target.value = '';
    if (!file) return;
    setError(null);
    if (!ACCEPTED_TYPES.includes(file.type)) { setError('Unsupported format. Please use PNG, SVG, JPG or WEBP.'); return; }
    if (file.size > MAX_SIZE) { setError('File too large. Maximum size is 5MB.'); return; }
    setPending(file);
  }

  return (
    <div className="fld" style={{ gridColumn: '1/-1' }}>
      <label>Company Logo</label>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        <div style={{ width: 64, height: 64, borderRadius: 14, border: value ? 'none' : '1px solid var(--bdr)', background: value ? 'transparent' : '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden', flexShrink: 0 }}>
          {value
            ? <img src={value} alt="Company logo" style={{ width: '100%', height: '100%', objectFit: 'contain' }} />
            : <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="var(--txt3,#9CA3AF)" strokeWidth="1.6"><path d="M3 21h18M9 8h1m-1 4h1m4-4h1m-1 4h1M5 21V5a2 2 0 012-2h10a2 2 0 012 2v16" /></svg>}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          <div style={{ display: 'flex', gap: 8 }}>
            <button type="button" className="om-lg-btn" onClick={pickFile}>{value ? 'Change Logo' : 'Upload Logo'}</button>
            {value && <button type="button" className="om-lg-btn" onClick={onRemove}>Remove</button>}
          </div>
          <span style={{ fontSize: 10.5, color: 'var(--txt3,#9CA3AF)' }}>PNG, SVG, JPG or WEBP · up to 5MB · optional</span>
          {error && <span style={{ fontSize: 11, color: '#DC2626', fontWeight: 600 }}>{error}</span>}
        </div>
        <input ref={inputRef} type="file" accept=".png,.svg,.jpg,.jpeg,.webp,image/png,image/svg+xml,image/jpeg,image/webp" style={{ display: 'none' }} onChange={handleFile} />
      </div>
      {pending && (
        <LogoCropEditor file={pending} onCancel={() => setPending(null)} onSave={(dataUrl) => { onChange(dataUrl); setPending(null); }} />
      )}
    </div>
  );
}

Object.assign(window, { CompanyLogoField, CompanyLogoThumb, LogoFallbackIcon, OM_GROUP_MARK });
