// src/features/messages/ui/attachment-preview.jsx
//
// One attachment rendered. Images inline (signed URL fetched on mount,
// shown at max-width 240); PDFs as a click-to-open pill.

const AttachmentPreview = ({ attachment }) => {
  const a = attachment;
  const isImage = a.mime_type && a.mime_type.startsWith('image/');
  const isHeic  = a.mime_type === 'image/heic';
  const isPdf   = a.mime_type === 'application/pdf';

  const [signedUrl, setSignedUrl] = React.useState(null);
  const [err,       setErr]       = React.useState(null);

  React.useEffect(() => {
    let cancel = false;
    (async () => {
      try {
        const url = await window.Messages.db.signAttachmentUrl(a.storage_path);
        if (!cancel) setSignedUrl(url);
      } catch (e) { if (!cancel) setErr(e.message || String(e)); }
    })();
    return () => { cancel = true; };
  }, [a.storage_path]);

  const open = () => { if (signedUrl) window.open(signedUrl, '_blank', 'noopener'); };

  if (err) {
    return <div style={{ fontSize:11, color:'oklch(40% 0.1 25)' }}>Failed to load {a.filename}</div>;
  }

  if (isImage && !isHeic && signedUrl) {
    return (
      <a href={signedUrl} target="_blank" rel="noopener" style={{ display:'inline-block', marginTop:4 }}>
        <img src={signedUrl} alt={a.filename}
          style={{ display:'block', maxWidth:240, maxHeight:240, borderRadius:8, border:'1px solid oklch(90% 0.01 265)' }} />
      </a>
    );
  }

  // PDF (or HEIC, or any non-renderable image) → pill
  const label = a.filename || (isPdf ? 'PDF' : 'File');
  const tag   = isPdf ? 'PDF' : (isImage ? 'IMG' : 'FILE');
  return (
    <button onClick={open} disabled={!signedUrl}
      style={{ display:'inline-flex', alignItems:'center', gap:8, marginTop:4,
               padding:'8px 12px', background:'oklch(96% 0.005 60)',
               border:'1px solid oklch(90% 0.01 265)', borderRadius:8,
               fontSize:12, fontWeight:600, color:'oklch(22% 0.06 265)',
               cursor: signedUrl ? 'pointer' : 'wait',
               fontFamily:"'Plus Jakarta Sans', sans-serif", textAlign:'left',
               maxWidth:280 }}>
      <span style={{ fontSize:10, fontWeight:700, padding:'2px 6px',
                     background:'oklch(22% 0.06 265)', color:'#fff',
                     borderRadius:4, letterSpacing:'0.05em' }}>{tag}</span>
      <span style={{ overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{label}</span>
    </button>
  );
};

window.Messages.ui.AttachmentPreview = AttachmentPreview;
window.AttachmentPreview              = AttachmentPreview;
