/**
 * Field Capture — מגירת ריג'קטים ממתינים לאישור
 * Section A: pending batches from external sources (Claude chat / WhatsApp / API)
 * Section B: manual direct-reject entry
 * Section C: approved today (read-only info)
 */
(function () {
const { useState, useEffect, useRef, useCallback } = React;

// ── Helpers ──────────────────────────────────────────────────────────────────
const WEBHOOK_DEFAULTS = {
  PLACEHOLDER_PENDING_REJECTS_INBOX: 'https://hook.eu2.make.com/o7h1izhhip0gb2qutw9at5uatxbr4msj',
  PLACEHOLDER_LIST_PENDING_REJECTS:  'https://hook.eu2.make.com/39lz9wg678cauim9k8dbgyp5tmtx9k81',
  PLACEHOLDER_APPROVE_PENDING_BATCH: 'https://hook.eu2.make.com/9ujt7a9wqeb65cxg30vk3tf9y3e7o741',
};

function getWebhookUrl(key) {
  try {
    const s = JSON.parse(localStorage.getItem('ybp_settings') || '{}');
    return (s.webhooks || {})[key] || WEBHOOK_DEFAULTS[key] || '';
  } catch { return WEBHOOK_DEFAULTS[key] || ''; }
}

function getSecurityKey() {
  try {
    const s = JSON.parse(localStorage.getItem('ybp_settings') || '{}');
    return (s.webhooks || {})._securityKey || '1h4M4SEXbhoYF1YVW1mS6YJZs84yxSVHaBjPDDxMpbak';
  } catch { return '1h4M4SEXbhoYF1YVW1mS6YJZs84yxSVHaBjPDDxMpbak'; }
}

function getUserId() {
  try {
    const sess = JSON.parse(localStorage.getItem('ybp_auth_session') || '{}');
    return sess.email || 'ykcafe26@gmail.com';
  } catch { return 'ykcafe26@gmail.com'; }
}

async function fetchPendingBatches() {
  const url = getWebhookUrl('PLACEHOLDER_LIST_PENDING_REJECTS');
  if (!url) return [];
  try {
    const userId = getUserId();
    const sk = getSecurityKey();
    const resp = await fetch(
      `${url}?userId=${encodeURIComponent(userId)}&_sk=${encodeURIComponent(sk)}`
    );
    if (!resp.ok) return [];
    const data = await resp.json();
    return data.items || [];
  } catch { return []; }
}

async function approveBatch(batchId, action) {
  const url = getWebhookUrl('PLACEHOLDER_APPROVE_PENDING_BATCH');
  if (!url) return; // silent — local state is already updated
  const resp = await fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ _sk: getSecurityKey(), batchId, action }),
  });
  if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
}

const fmtDateHe = (iso) => {
  if (!iso) return '';
  const [y, m, d] = (iso || '').slice(0, 10).split('-');
  return `${d || ''}/${m || ''}/${y || ''}`;
};

const defaultDue = () => {
  const d = new Date();
  d.setDate(d.getDate() + 7);
  return d.toISOString().slice(0, 10);
};

// ── Constants ─────────────────────────────────────────────────────────────────
const SEV_COLORS = {
  critical: { bg: '#fee2e2', color: '#dc2626' },
  high:     { bg: '#ffedd5', color: '#c2410c' },
  medium:   { bg: '#fef3c7', color: '#b45309' },
  low:      { bg: '#f0fdf4', color: '#16a34a' },
};
const SEV_LABELS   = { critical: 'קריטי', high: 'גבוה', medium: 'בינוני', low: 'נמוך' };
const SRC_LABELS   = { claude_chat: 'Claude Chat', whatsapp: 'WhatsApp', manual: 'ידני', curl: 'API' };
const SRC_ICONS    = { claude_chat: '🤖', whatsapp: '💬', manual: '✏️', curl: '⚡' };

const inputStyle = {
  width: '100%', padding: '7px 10px', borderRadius: 6,
  border: '1px solid var(--ybp-border,#e5e7eb)',
  background: 'var(--ybp-input-bg,#fff)', color: 'var(--ybp-ink,#111827)',
  fontFamily: 'Assistant, sans-serif', fontSize: 13, boxSizing: 'border-box',
};

// ── BatchCard ─────────────────────────────────────────────────────────────────
const BatchCard = ({ batch, projects, onApprove, onReject }) => {
  const [rejects, setRejects] = useState(() => batch.rejects || []);
  const [expanded, setExpanded] = useState(true);
  const [loading, setLoading]   = useState(false);
  const photoRef = useRef(null);
  const [photoTarget, setPhotoTarget] = useState(null); // index of reject

  const projectName =
    batch.projectName ||
    (projects.find(p => p.id === batch.projectId)?.name) ||
    'פרויקט לא זוהה';
  const srcLabel = SRC_LABELS[batch.source] || batch.source || 'חיצוני';
  const srcIcon  = SRC_ICONS[batch.source] || '📥';

  const updateReject = (idx, fields) =>
    setRejects(prev => prev.map((r, i) => i === idx ? { ...r, ...fields } : r));

  const openPhoto = (idx) => {
    setPhotoTarget(idx);
    photoRef.current?.click();
  };

  const onPhotoFile = (e) => {
    const file = e.target.files?.[0];
    if (!file || photoTarget === null) return;
    const reader = new FileReader();
    reader.onload = (ev) => {
      updateReject(photoTarget, {
        photos: [...(rejects[photoTarget]?.photos || []), ev.target.result],
      });
    };
    reader.readAsDataURL(file);
    e.target.value = '';
  };

  const handleApprove = async () => {
    setLoading(true);
    try { await onApprove(batch.batchId, rejects); }
    finally { setLoading(false); }
  };

  return (
    <div style={{
      border: '1px solid #fecaca', borderRadius: 12, overflow: 'hidden',
      marginBottom: 12, background: 'var(--ybp-card-bg,#fff)',
    }}>
      {/* Header */}
      <div
        onClick={() => setExpanded(e => !e)}
        style={{
          padding: '12px 16px', cursor: 'pointer', background: '#fef2f2',
          borderBottom: expanded ? '1px solid #fecaca' : 'none',
          display: 'flex', alignItems: 'center', gap: 10, direction: 'rtl',
        }}
      >
        <span style={{ fontSize: 18 }}>{srcIcon}</span>
        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: 700, fontSize: 14, color: '#111827' }}>
            {srcLabel} — {rejects.length} ריג'קטים
          </div>
          <div style={{ fontSize: 12, color: '#6b7280', marginTop: 2 }}>
            פרויקט: <strong>{projectName}</strong>
            {batch.createdAt ? ` · ${fmtDateHe(batch.createdAt.slice(0, 10))}` : ''}
          </div>
        </div>
        <span style={{ fontSize: 12, color: '#6b7280' }}>{expanded ? '▲' : '▼'}</span>
      </div>

      {expanded && (
        <div style={{ padding: 12 }}>
          <input
            ref={photoRef} type="file" accept="image/*" capture="environment"
            style={{ display: 'none' }} onChange={onPhotoFile}
          />

          {rejects.map((r, idx) => (
            <div key={r.tempId || idx} style={{
              border: '1px solid var(--ybp-border,#e5e7eb)',
              borderRadius: 8, padding: '10px 12px', marginBottom: 8, direction: 'rtl',
            }}>
              {/* Title row */}
              <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 6 }}>
                <input
                  value={r.title}
                  onChange={e => updateReject(idx, { title: e.target.value })}
                  style={{
                    flex: 1, fontWeight: 600, fontSize: 13,
                    border: 'none', borderBottom: '1px solid var(--ybp-border,#e5e7eb)',
                    background: 'transparent', color: 'var(--ybp-ink,#111827)',
                    fontFamily: 'Assistant, sans-serif', padding: '2px 0',
                  }}
                  placeholder="כותרת ריג'קט"
                />
                <select
                  value={r.severity || 'medium'}
                  onChange={e => updateReject(idx, { severity: e.target.value })}
                  style={{
                    fontSize: 11, fontWeight: 700, border: 'none',
                    borderRadius: 99, padding: '2px 8px', cursor: 'pointer',
                    background: SEV_COLORS[r.severity]?.bg || '#f3f4f6',
                    color: SEV_COLORS[r.severity]?.color || '#374151',
                    fontFamily: 'Assistant, sans-serif',
                  }}
                >
                  {Object.entries(SEV_LABELS).map(([k, v]) => (
                    <option key={k} value={k}>{v}</option>
                  ))}
                </select>
              </div>

              {r.description && (
                <div style={{ fontSize: 12, color: 'var(--ybp-ink-faint,#6b7280)', marginBottom: 6 }}>
                  {r.description}
                </div>
              )}

              {/* Meta row */}
              <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
                {r.location && (
                  <span style={{ fontSize: 11, color: '#6b7280' }}>📍 {r.location}</span>
                )}
                <input
                  value={r.assignee || ''}
                  onChange={e => updateReject(idx, { assignee: e.target.value })}
                  style={{
                    fontSize: 11, border: '1px solid var(--ybp-border,#e5e7eb)',
                    borderRadius: 4, padding: '2px 6px', background: 'transparent',
                    color: 'var(--ybp-ink,#111827)', fontFamily: 'Assistant, sans-serif',
                    width: 90,
                  }}
                  placeholder="אחראי"
                />
                {r.due && (
                  <span style={{ fontSize: 11, color: '#6b7280' }}>📅 {fmtDateHe(r.due)}</span>
                )}
                {/* Photos */}
                {(r.photos || []).map((ph, pi) => (
                  <img key={pi} src={ph} alt="" style={{
                    width: 36, height: 36, objectFit: 'cover', borderRadius: 4,
                    border: '1px solid var(--ybp-border,#e5e7eb)', flexShrink: 0,
                  }} />
                ))}
                <button
                  onClick={() => openPhoto(idx)}
                  style={{
                    background: 'none', border: '1px dashed #d1d5db',
                    borderRadius: 4, padding: '2px 8px', cursor: 'pointer',
                    fontSize: 14, color: '#9ca3af',
                  }}
                  title="הוסף תמונה"
                >📷</button>
              </div>
            </div>
          ))}

          {/* Actions */}
          <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 8 }}>
            <button
              onClick={() => onReject(batch.batchId)}
              style={{
                padding: '7px 14px', borderRadius: 6,
                border: '1px solid #e5e7eb', background: 'none',
                color: '#6b7280', cursor: 'pointer', fontSize: 13,
                fontFamily: 'Assistant, sans-serif',
              }}
            >✕ דחה</button>
            <button
              onClick={handleApprove}
              disabled={loading}
              style={{
                padding: '7px 16px', borderRadius: 6,
                background: '#16a34a', color: '#fff', border: 'none',
                cursor: loading ? 'wait' : 'pointer',
                fontSize: 13, fontWeight: 700, fontFamily: 'Assistant, sans-serif',
                opacity: loading ? 0.7 : 1,
              }}
            >{loading ? '...' : `✓ אשר ${rejects.length} ריג'קטים`}</button>
          </div>
        </div>
      )}
    </div>
  );
};

// ── ManualEntryForm ───────────────────────────────────────────────────────────
const emptyManual = () => ({
  title: '', description: '', location: '', trades: [],
  assignee: '', severity: 'medium', due: defaultDue(), photos: [],
});

const ManualEntryForm = ({ projectId, onAdded }) => {
  const [form, setForm]         = useState(emptyManual);
  const [expanded, setExpanded] = useState(false);
  const [submitting, setSubmitting] = useState(false);
  const photoRef = useRef(null);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const onPhotoFile = (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (ev) => set('photos', [...form.photos, ev.target.result]);
    reader.readAsDataURL(file);
    e.target.value = '';
  };

  const handleSubmit = () => {
    if (!form.title.trim()) { alert("נדרשת כותרת"); return; }
    setSubmitting(true);
    try {
      const pid = projectId || (YBP_DATA.projects[0]?.id);
      SyncStore.addDirectReject(pid, {
        title: form.title,
        description: form.description,
        location: form.location,
        trades: form.trades,
        assignee: form.assignee,
        severity: form.severity,
        due: form.due,
        photos: form.photos,
      });
      setForm(emptyManual());
      window.toastSuccess && window.toastSuccess("ריג'קט נוסף");
      onAdded && onAdded();
    } finally { setSubmitting(false); }
  };

  return (
    <div style={{
      border: '1px solid var(--ybp-border,#e5e7eb)',
      borderRadius: 12, overflow: 'hidden', marginBottom: 12,
      background: 'var(--ybp-card-bg,#fff)',
    }}>
      <div
        onClick={() => setExpanded(e => !e)}
        style={{
          padding: '12px 16px', cursor: 'pointer',
          background: 'var(--ybp-panel,#f9fafb)',
          display: 'flex', alignItems: 'center', gap: 10, direction: 'rtl',
        }}
      >
        <span style={{ fontSize: 18 }}>✏️</span>
        <div style={{ flex: 1, fontWeight: 600, fontSize: 14, color: 'var(--ybp-ink,#111827)' }}>
          הקלדה ידנית — ריג'קט חדש
        </div>
        <span style={{ fontSize: 13, color: '#2563eb', fontWeight: 600 }}>
          {expanded ? '▲ סגור' : '▼ פתח'}
        </span>
      </div>

      {expanded && (
        <div style={{ padding: 16, direction: 'rtl' }}>
          <input
            ref={photoRef} type="file" accept="image/*" capture="environment"
            style={{ display: 'none' }} onChange={onPhotoFile}
          />

          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 10 }}>
            <div style={{ gridColumn: '1 / -1' }}>
              <label style={{ fontSize: 12, color: '#6b7280', display: 'block', marginBottom: 3 }}>כותרת *</label>
              <input value={form.title} onChange={e => set('title', e.target.value)}
                style={inputStyle} placeholder="תאר את הריג'קט בקצרה" />
            </div>
            <div style={{ gridColumn: '1 / -1' }}>
              <label style={{ fontSize: 12, color: '#6b7280', display: 'block', marginBottom: 3 }}>תיאור</label>
              <textarea value={form.description} onChange={e => set('description', e.target.value)}
                rows={2} style={{ ...inputStyle, resize: 'vertical' }} placeholder="פרטים נוספים..." />
            </div>
            <div>
              <label style={{ fontSize: 12, color: '#6b7280', display: 'block', marginBottom: 3 }}>מיקום</label>
              <input value={form.location} onChange={e => set('location', e.target.value)}
                style={inputStyle} placeholder="קומה / חדר" />
            </div>
            <div>
              <label style={{ fontSize: 12, color: '#6b7280', display: 'block', marginBottom: 3 }}>אחראי</label>
              <input value={form.assignee} onChange={e => set('assignee', e.target.value)}
                style={inputStyle} placeholder="שם קבלן / איש קשר" />
            </div>
            <div>
              <label style={{ fontSize: 12, color: '#6b7280', display: 'block', marginBottom: 3 }}>חומרה</label>
              <select value={form.severity} onChange={e => set('severity', e.target.value)} style={inputStyle}>
                {Object.entries(SEV_LABELS).map(([k, v]) => <option key={k} value={k}>{v}</option>)}
              </select>
            </div>
            <div>
              <label style={{ fontSize: 12, color: '#6b7280', display: 'block', marginBottom: 3 }}>תאריך יעד</label>
              <input type="date" value={form.due} onChange={e => set('due', e.target.value)} style={inputStyle} />
            </div>
          </div>

          {/* Photos */}
          <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 14, flexWrap: 'wrap' }}>
            {form.photos.map((ph, i) => (
              <div key={i} style={{ position: 'relative' }}>
                <img src={ph} alt="" style={{
                  width: 52, height: 52, objectFit: 'cover', borderRadius: 6,
                  border: '1px solid var(--ybp-border,#e5e7eb)',
                }} />
                <button onClick={() => set('photos', form.photos.filter((_, j) => j !== i))}
                  style={{
                    position: 'absolute', top: -5, right: -5,
                    width: 18, height: 18, borderRadius: '50%',
                    background: '#dc2626', color: '#fff', border: 'none',
                    cursor: 'pointer', fontSize: 10,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>✕</button>
              </div>
            ))}
            <button onClick={() => photoRef.current?.click()} style={{
              width: 52, height: 52, borderRadius: 6,
              border: '1px dashed #d1d5db', background: 'none',
              cursor: 'pointer', fontSize: 22, color: '#9ca3af',
            }}>📷</button>
          </div>

          <button
            onClick={handleSubmit}
            disabled={submitting || !form.title.trim()}
            style={{
              width: '100%', padding: 10, borderRadius: 8,
              background: '#1a2c4a', color: '#fff', border: 'none',
              cursor: !form.title.trim() ? 'not-allowed' : 'pointer',
              fontSize: 14, fontWeight: 700, fontFamily: 'Assistant, sans-serif',
              opacity: !form.title.trim() ? 0.5 : 1,
            }}
          >+ הוסף ריג'קט ישירות</button>
        </div>
      )}
    </div>
  );
};

// ── FieldCaptureScreen ────────────────────────────────────────────────────────
const FieldCaptureScreen = ({ projectId, onBack }) => {
  const [store, setStore]               = useState(() => SyncStore.get());
  const [pendingBatches, setPending]    = useState([]);
  const [loading, setLoading]           = useState(false);
  const { isMobile }                    = useViewport();
  const projects                        = YBP_DATA.projects || [];

  useEffect(() => SyncStore.subscribe(setStore), []);

  const doFetch = useCallback(async () => {
    setLoading(true);
    try { setPending(await fetchPendingBatches()); }
    finally { setLoading(false); }
  }, []);

  useEffect(() => { doFetch(); }, [doFetch]);

  // Section C: direct rejects added/approved today
  const today = new Date().toISOString().slice(0, 10);
  const todayApproved = (store.directRejects || []).filter(r =>
    (!projectId || r.projectId === projectId) &&
    (r.createdAt || '').slice(0, 10) === today
  );

  const handleApprove = async (batchId, updatedRejects) => {
    const batch = pendingBatches.find(b => b.batchId === batchId);
    if (!batch) return;
    const pid = batch.projectId || projectId || (projects[0]?.id);

    updatedRejects.forEach(r => {
      SyncStore.addDirectReject(pid, {
        title:       r.title || '(ללא כותרת)',
        description: r.description || '',
        location:    r.location || '',
        trades:      r.trades || [],
        assignee:    r.assignee || '',
        severity:    r.severity || 'medium',
        due:         r.due || defaultDue(),
        photos:      r.photos || [],
      });
    });

    try { await approveBatch(batchId, 'approve'); }
    catch (e) { console.warn('[FieldCapture] approve webhook failed:', e); }

    setPending(prev => prev.filter(b => b.batchId !== batchId));
    window.toastSuccess && window.toastSuccess(`${updatedRejects.length} ריג'קטים אושרו ✓`);
  };

  const handleReject = async (batchId) => {
    try { await approveBatch(batchId, 'reject'); }
    catch (e) { console.warn('[FieldCapture] reject webhook failed:', e); }
    setPending(prev => prev.filter(b => b.batchId !== batchId));
    window.toastSuccess && window.toastSuccess('Batch נדחה');
  };

  const totalPending = pendingBatches.reduce((s, b) => s + (b.rejects?.length || 0), 0);

  return (
    <div style={{
      minHeight: '100vh', paddingBottom: 80,
      background: 'var(--ybp-bg,#f6f7f9)',
      fontFamily: 'Assistant, sans-serif', direction: 'rtl',
    }}>
      {/* Header */}
      <div style={{
        padding: '16px 20px', background: 'var(--ybp-panel,#fff)',
        borderBottom: '1px solid var(--ybp-border,#e5e7eb)',
        display: 'flex', alignItems: 'center', gap: 12, direction: 'rtl',
      }}>
        {onBack && (
          <button onClick={onBack} style={{
            background: 'none', border: 'none', cursor: 'pointer',
            fontSize: 22, color: 'var(--ybp-ink-soft,#374151)', lineHeight: 1,
          }}>›</button>
        )}
        <div style={{ flex: 1 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <h2 style={{ margin: 0, fontSize: 18, fontWeight: 800, color: 'var(--ybp-ink,#111827)' }}>
              📥 Field Capture
            </h2>
            {totalPending > 0 && (
              <span style={{
                background: '#dc2626', color: '#fff',
                fontSize: 12, fontWeight: 700,
                padding: '1px 8px', borderRadius: 99,
              }}>{totalPending} ממתינים</span>
            )}
          </div>
          <div style={{ fontSize: 12, color: '#6b7280', marginTop: 2 }}>
            קליטת ריג'קטים ממקורות שונים
          </div>
        </div>
        <button
          onClick={doFetch} disabled={loading}
          style={{
            background: 'none', border: '1px solid var(--ybp-border,#e5e7eb)',
            borderRadius: 6, padding: '5px 12px', cursor: 'pointer',
            fontSize: 12, color: 'var(--ybp-ink-soft,#374151)',
            fontFamily: 'Assistant, sans-serif',
          }}
        >{loading ? '...' : '↻ רענן'}</button>
      </div>

      <div style={{ padding: '20px', maxWidth: 720, margin: '0 auto' }}>

        {/* ── Section A: ממתינים לאישור ─────────────────────────────────── */}
        {pendingBatches.length > 0 && (
          <div style={{ marginBottom: 28 }}>
            <h3 style={{ margin: '0 0 12px', fontSize: 15, fontWeight: 700, color: '#dc2626' }}>
              🔔 ריג'קטים מבחוץ — ממתינים לאישור
            </h3>
            {pendingBatches.map(batch => (
              <BatchCard
                key={batch.batchId}
                batch={batch}
                projects={projects}
                onApprove={handleApprove}
                onReject={handleReject}
              />
            ))}
          </div>
        )}

        {pendingBatches.length === 0 && !loading && (
          <div style={{
            border: '1px dashed var(--ybp-border,#e5e7eb)',
            borderRadius: 12, padding: '20px', marginBottom: 28,
            textAlign: 'center', color: '#9ca3af', fontSize: 13,
          }}>
            ✅ אין ריג'קטים ממתינים מבחוץ
            <div style={{ fontSize: 11, marginTop: 4 }}>
              שלח POST ל-PLACEHOLDER_PENDING_REJECTS_INBOX כדי לקלוט ריג'קטים
            </div>
          </div>
        )}

        {/* ── Section B: הקלדה ידנית ────────────────────────────────────── */}
        <div style={{ marginBottom: 28 }}>
          <h3 style={{ margin: '0 0 12px', fontSize: 15, fontWeight: 700, color: 'var(--ybp-ink,#111827)' }}>
            ✏️ הקלדה ידנית
          </h3>
          <ManualEntryForm projectId={projectId} onAdded={() => {}} />
        </div>

        {/* ── Section C: אושרו היום ─────────────────────────────────────── */}
        {todayApproved.length > 0 && (
          <div style={{ marginBottom: 28 }}>
            <h3 style={{ margin: '0 0 12px', fontSize: 15, fontWeight: 700, color: 'var(--ybp-ink,#111827)' }}>
              ✅ אושרו היום ({todayApproved.length})
            </h3>
            <div style={{
              border: '1px solid var(--ybp-border,#e5e7eb)',
              borderRadius: 12, overflow: 'hidden',
              background: 'var(--ybp-card-bg,#fff)',
            }}>
              {todayApproved.map((r, i) => {
                const proj = projects.find(p => p.id === r.projectId);
                return (
                  <div key={r.id} style={{
                    padding: '10px 16px', direction: 'rtl',
                    borderBottom: i < todayApproved.length - 1
                      ? '1px solid var(--ybp-border,#e5e7eb)' : 'none',
                    display: 'flex', alignItems: 'center', gap: 10,
                  }}>
                    <span style={{
                      padding: '2px 7px', borderRadius: 99,
                      fontSize: 11, fontWeight: 700, flexShrink: 0,
                      background: SEV_COLORS[r.severity]?.bg || '#f3f4f6',
                      color: SEV_COLORS[r.severity]?.color || '#374151',
                    }}>{SEV_LABELS[r.severity] || r.severity}</span>
                    <span style={{
                      flex: 1, fontSize: 13, fontWeight: 600,
                      color: 'var(--ybp-ink,#111827)',
                    }}>{r.title}</span>
                    {proj && (
                      <span style={{ fontSize: 11, color: '#9ca3af', flexShrink: 0 }}>
                        {proj.name}
                      </span>
                    )}
                    {r.location && (
                      <span style={{ fontSize: 11, color: '#6b7280', flexShrink: 0 }}>
                        📍 {r.location}
                      </span>
                    )}
                    {r.assignee && (
                      <span style={{ fontSize: 11, color: '#6b7280', flexShrink: 0 }}>
                        {r.assignee}
                      </span>
                    )}
                  </div>
                );
              })}
            </div>
          </div>
        )}

      </div>
    </div>
  );
};

// ── Exports ───────────────────────────────────────────────────────────────────
window.FieldCaptureScreen      = FieldCaptureScreen;
window.fetchPendingRejectBatches = fetchPendingBatches;

})();
