// Shared image upload hook — persists to sessionStorage by key
function useImageUpload(key) {
  const [img, setImg] = useState(() => sessionStorage.getItem(key) || null);
  const inputRef = useRef(null);
  const load = (file) => {
    if (!file || !file.type.startsWith('image/')) return;
    const reader = new FileReader();
    reader.onload = (e) => {
      setImg(e.target.result);
      try { sessionStorage.setItem(key, e.target.result); } catch {}
    };
    reader.readAsDataURL(file);
  };
  const trigger = () => inputRef.current?.click();
  const clear = () => { setImg(null); sessionStorage.removeItem(key); };
  const inputEl = (
    <input ref={inputRef} type="file" accept="image/*" style={{ display: 'none' }}
      onChange={(e) => load(e.target.files[0])} />
  );
  return { img, load, trigger, clear, inputEl };
}

// Generic upload slot with corner brackets, drag-drop, placeholder
function UploadSlot({ uploadKey, label = 'adicionar imagem', placeholder, style, imgStyle, children, onClick }) {
  const { img, load, trigger, clear, inputEl } = useImageUpload(uploadKey);
  const [drag, setDrag] = useState(false);

  const handleClick = () => { if (onClick) onClick(); else trigger(); };

  return (
    <div
      onClick={handleClick}
      onDragOver={(e) => { e.preventDefault(); setDrag(true); }}
      onDragLeave={() => setDrag(false)}
      onDrop={(e) => { e.preventDefault(); setDrag(false); load(e.dataTransfer.files[0]); }}
      style={{ position: 'relative', cursor: 'pointer', ...style }}
    >
      {/* Corner brackets */}
      {[['tl',0,0],['tr',null,0],['bl',0,null],['br',null,null]].map(([k,l,t]) => (
        <span key={k} aria-hidden style={{
          position: 'absolute', zIndex: 3,
          left: l != null ? 0 : 'auto', right: l == null ? 0 : 'auto',
          top: t != null ? 0 : 'auto', bottom: t == null ? 0 : 'auto',
          width: 16, height: 16,
          borderTop: t != null ? `1.5px solid ${drag ? 'var(--accent)' : 'oklch(from var(--fg) l c h / 0.35)'}` : 'none',
          borderBottom: t == null ? `1.5px solid ${drag ? 'var(--accent)' : 'oklch(from var(--fg) l c h / 0.35)'}` : 'none',
          borderLeft: l != null ? `1.5px solid ${drag ? 'var(--accent)' : 'oklch(from var(--fg) l c h / 0.35)'}` : 'none',
          borderRight: l == null ? `1.5px solid ${drag ? 'var(--accent)' : 'oklch(from var(--fg) l c h / 0.35)'}` : 'none',
          transition: 'border-color .3s',
          pointerEvents: 'none',
        }} />
      ))}

      {img ? (
        <img src={img} alt={label} style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block', ...imgStyle }} />
      ) : (
        <div style={{
          width: '100%', height: '100%', minHeight: 80,
          display: 'flex', flexDirection: 'column',
          alignItems: 'center', justifyContent: 'center',
          gap: 8, padding: '12px',
          background: drag ? 'var(--accent-soft)' : 'transparent',
          transition: 'background .3s',
        }}>
          {placeholder || (
            <>
              <svg width="20" height="20" viewBox="0 0 20 20" fill="none" style={{ opacity: 0.35 }}>
                <path d="M3 14l4-4 3 3 3-4 4 5" stroke="currentColor" strokeWidth="1.2" strokeLinecap="round" strokeLinejoin="round"/>
                <circle cx="7" cy="8" r="1.5" stroke="currentColor" strokeWidth="1.2"/>
                <rect x="1" y="1" width="18" height="18" rx="1" stroke="currentColor" strokeWidth="1" strokeDasharray="3 2"/>
              </svg>
              <span className="mono" style={{ textAlign: 'center', lineHeight: 1.5, opacity: 0.55 }}>{label}</span>
            </>
          )}
        </div>
      )}

      {img && (
        <button onClick={(e) => { e.stopPropagation(); clear(); }} style={{
          position: 'absolute', top: 8, right: 8, zIndex: 4,
          background: 'oklch(0 0 0 / 0.55)', color: '#fff',
          border: 0, borderRadius: 999, padding: '4px 10px',
          fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.06em',
          cursor: 'pointer', textTransform: 'uppercase',
        }}>trocar</button>
      )}
      {children}
      {inputEl}
    </div>
  );
}

Object.assign(window, { useImageUpload, UploadSlot });
