const { Icon } = window.MarceloCasteloIODesignSystem_5e00d7;
const iconBtnStyle = { display: 'flex', alignItems: 'center', justifyContent: 'center', width: 30, height: 30, background: 'rgba(0,0,0,.6)', color: '#fff', border: 'none', borderRadius: 'var(--radius-sm)', cursor: 'pointer' };

/** Image block for article/chapter bodies: maximize (modal) + download controls. */
function ImageBlock({ slotId, caption }) {
  const ref = React.useRef(null);
  const [open, setOpen] = React.useState(null);
  const getSrc = () => {
    const el = ref.current;
    const img = el && el.shadowRoot && el.shadowRoot.querySelector('.frame img');
    return img && img.getAttribute('src') ? img.src : null;
  };
  return (
    <figure style={{ margin: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
      <div style={{ position: 'relative', width: '100%', aspectRatio: '16/9' }}>
        <image-slot ref={ref} id={slotId} shape="rounded" radius="10" placeholder="Imagem do artigo"></image-slot>
        <div style={{ position: 'absolute', top: 10, right: 10, display: 'flex', gap: 6 }}>
          <button title="Maximizar" onClick={() => { const s = getSrc(); if (s) setOpen(s); }} style={iconBtnStyle}><Icon name="maximize-2" size={14} /></button>
          <button title="Baixar imagem" onClick={() => { const s = getSrc(); if (!s) return; const a = document.createElement('a'); a.href = s; a.download = (slotId || 'imagem') + '.webp'; document.body.appendChild(a); a.click(); a.remove(); }} style={iconBtnStyle}><Icon name="download" size={14} /></button>
        </div>
      </div>
      {caption && <figcaption style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-muted)' }}>{caption}</figcaption>}
      {open && (
        <div onClick={() => setOpen(null)} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,.85)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 999, cursor: 'zoom-out' }}>
          <img src={open} style={{ maxWidth: '90vw', maxHeight: '90vh', borderRadius: 'var(--radius-md)' }} onClick={(e) => e.stopPropagation()} />
        </div>
      )}
    </figure>
  );
}

/** Optional small cover image for a sidebar ad card. */
function SidebarAdImage({ slotId }) {
  return <div style={{ width: '100%', aspectRatio: '16/9', borderRadius: 'var(--radius-md) var(--radius-md) 0 0', overflow: 'hidden' }}><image-slot id={slotId} shape="rect" placeholder="Capa (opcional)"></image-slot></div>;
}
Object.assign(window, { ImageBlock, SidebarAdImage });
