// Primus IQ — File View Modal (inline preview + details + actions)

const FileViewModal = ({ file, onClose, onDownload }) => {
  const [viewUrl, setViewUrl] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState('');

  // Fetch an inline (preview) signed URL when a file is opened.
  React.useEffect(() => {
    if (!file) return;
    setViewUrl(null); setError(''); setLoading(true);
    // 'pending-*' ids are client-side placeholders for a queued import, not real
    // artifact UUIDs — don't fetch a preview URL that can't exist yet.
    if (String(file.id || '').startsWith('pending')) {
      setLoading(false);
      setError('This file is still being imported — the preview will be available once it finishes.');
      return;
    }
    PrimusAPI.getViewUrl(file.id)
      .then(r => setViewUrl(typeof r === 'string' ? r : (r.download_url || r.url)))
      .catch(ex => setError(ex.status === 403
        ? 'You do not have permission to view this file.'
        : (ex.message || 'Could not load the preview.')))
      .finally(() => setLoading(false));
  }, [file && file.id]);

  // Esc to close
  React.useEffect(() => {
    if (!file) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [file]);

  if (!file) return null;

  const ext = (file.ext || '').toLowerCase();
  const isImage = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg'].includes(ext);
  const isPdf = ext === 'pdf';
  const canPreview = isImage || isPdf;
  const meta = [ext ? ext.toUpperCase() : null, file.size, file.added || file.modified].filter(Boolean).join(' · ');

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 70,
      background: 'var(--bg-overlay)', backdropFilter: 'blur(4px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      animation: 'fadein 0.18s ease-out',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: 880, maxWidth: '94vw', height: 680, maxHeight: '92vh',
        background: 'var(--bg-card)', borderRadius: 16,
        boxShadow: 'var(--shadow-lg), 0 0 0 1px var(--line)',
        display: 'flex', flexDirection: 'column', overflow: 'hidden',
        animation: 'rise 0.22s ease-out',
      }}>
        {/* Header */}
        <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 12 }}>
          <FileBadge ext={ext} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 15, fontWeight: 600, color: 'var(--ink)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{file.name}</div>
            <div style={{ fontSize: 11.5, color: 'var(--mute)', marginTop: 3, display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
              {meta && <span>{meta}</span>}
              {file.conf && <span className={`conf ${file.conf}`} style={{ padding: '1px 6px', fontSize: 10 }}>{CONF_LABELS[file.conf] || file.conf}</span>}
              {(file.tags || []).slice(0, 5).map(t => (
                <span key={t} style={{ fontSize: 10, color: 'var(--maroon)', background: 'var(--maroon-06)', padding: '1px 6px', borderRadius: 5 }}>{t}</span>
              ))}
            </div>
          </div>
          <button onClick={onClose} style={{ width: 30, height: 30, borderRadius: 8, background: 'transparent', border: 'none', cursor: 'pointer', display: 'grid', placeItems: 'center', color: 'var(--mute)' }}>
            <svg width="14" height="14" viewBox="0 0 14 14"><path d="M2 2l10 10M12 2L2 12" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>
          </button>
        </div>

        {/* Preview */}
        <div style={{ flex: 1, minHeight: 0, background: 'var(--bg-soft)', display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'auto' }}>
          {loading ? (
            <div style={{ fontSize: 13, color: 'var(--mute)' }}>Loading preview…</div>
          ) : error ? (
            <div style={{ fontSize: 13, color: 'var(--maroon)', padding: 24, textAlign: 'center', maxWidth: 420 }}>{error}</div>
          ) : !canPreview ? (
            <div style={{ textAlign: 'center', padding: 24, color: 'var(--mute)' }}>
              <div style={{ fontSize: 34, marginBottom: 10 }}>📄</div>
              <div style={{ fontSize: 13, color: 'var(--ink-2)' }}>Preview isn't available for {ext ? `.${ext}` : 'this'} files.</div>
              <div style={{ fontSize: 12, marginTop: 4 }}>Use Download to open it.</div>
            </div>
          ) : isImage ? (
            <img src={viewUrl} alt={file.name} style={{ maxWidth: '100%', maxHeight: '100%', objectFit: 'contain' }} />
          ) : (
            <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}>
              <iframe src={viewUrl} title={file.name} style={{ flex: 1, border: 'none', width: '100%' }} />
              <div style={{ padding: '6px 12px', background: 'var(--bg-soft)', borderTop: '1px solid var(--line)', fontSize: 11.5, color: 'var(--mute)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <span>If the preview didn't load, your browser may have downloaded it instead.</span>
                <a href={viewUrl} target="_blank" rel="noopener noreferrer" style={{ color: 'var(--maroon)', fontWeight: 600, textDecoration: 'none', whiteSpace: 'nowrap', marginLeft: 12 }}>Open in new tab →</a>
              </div>
            </div>
          )}
        </div>

        {/* Footer actions */}
        <div style={{ padding: '12px 18px', borderTop: '1px solid var(--line)', display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
          <button onClick={onClose} className="btn-secondary" style={{ height: 36 }}>Close</button>
          {onDownload && <button onClick={onDownload} className="btn-primary" style={{ height: 36 }}>Download</button>}
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { FileViewModal });
