// Reports: Daily / Weekly / Rejects — hub + forms + viewer
(function(){
const { useState, useEffect, useMemo, useRef } = React;

// Trade list — בעלי מקצוע
const TRADES = [
  'חשמל','אינסטלציה','טיח וגבס','ריצוף','צבע','מיזוג','אלומיניום',
  'נגרות','מטבחים','ריתוך ומסגרות','איטום','גינון','שיש ואבן','בטיחות',
];

const SEVERITY_OPTS = [
  { k: 'critical', label: 'קריטי',  color: '#dc2626', bg: '#fee2e2' },
  { k: 'high',     label: 'גבוהה',  color: '#c2410c', bg: '#ffedd5' },
  { k: 'medium',   label: 'בינונית', color: '#d97706', bg: '#fef3c7' },
  { k: 'low',      label: 'נמוכה',  color: '#16a34a', bg: '#f0fdf4' },
];

const DAY_STATUS_OPTS = [
  { k: 'normal', label: 'יום עבודה רגיל', color: '#10b981' },
  { k: 'half',   label: 'חצי יום',        color: '#d97706' },
  { k: 'delay',  label: 'עיכוב',          color: '#dc2626' },
];

// Format helpers
const fmtDateHe = (iso) => {
  if (!iso) return '';
  const d = new Date(iso);
  return d.toLocaleDateString('he-IL', { day:'2-digit', month:'2-digit', year:'numeric' });
};
const todayISO = () => new Date().toISOString().slice(0,10);

// ── getActiveDrafts — מחזיר טיוטות פעילות מ-localStorage ───────────────────
function getActiveDrafts(filterProjectId) {
  const out = [];
  const KINDS = { daily: 'יומי', weekly: 'שבועי', rejects: 'ריג\'קטים', infra: 'תשתיות', meeting: 'סיכום פגישה' };
  const KIND_COLORS = { daily: '#1d4ed8', weekly: '#7c3aed', rejects: '#dc2626', infra: '#9333ea', meeting: '#0891b2' };
  for (let i = 0; i < localStorage.length; i++) {
    const k = localStorage.key(i);
    if (!k) continue;
    const match = k.match(/^ybp_cloud_ybp_draft_(daily|weekly|rejects|infra)_(.+)$/);
    if (!match) continue;
    // Strip trailing email suffix (userId) — daily/rejects keys end with _userId
    let pid = match[2];
    const lastUnderscore = pid.lastIndexOf('_');
    if (lastUnderscore > 0 && pid.slice(lastUnderscore + 1).includes('@')) {
      pid = pid.slice(0, lastUnderscore);
    }
    if (filterProjectId && pid !== filterProjectId) continue;
    try {
      const raw = JSON.parse(localStorage.getItem(k) || 'null');
      const data = raw?.data;
      if (!data || !data.savedAt) continue;
      const proj = (window.YBP_DATA?.projects || []).find(p => p.id === pid);
      out.push({
        localKey: k,
        draftKey: k.replace('ybp_cloud_', ''),
        kind: match[1],
        kindLabel: KINDS[match[1]] || match[1],
        kindColor: KIND_COLORS[match[1]] || '#6b7280',
        projectId: pid,
        projectName: proj?.name || '(' + pid + ')',
        savedAt: data.savedAt,
      });
    } catch {}
  }
  return out.sort((a, b) => b.savedAt - a.savedAt);
}

// ────────────────────────────────────────────────────────────────────
// HUB — entry screen showing all reports + create buttons
// ────────────────────────────────────────────────────────────────────
const ReportsHub = ({ projectId, onBack, onNewDaily, onNewWeekly, onNewRejects, onNewInfra, onNewInfraSurvey, onNewMeeting, onOpenSiteDoc, onOpenReport }) => {
  const project = YBP_DATA.projects.find(p => p.id === projectId);
  const [store, setStore] = useState(SyncStore.get());
  useEffect(() => SyncStore.subscribe(setStore), []);

  // Active drafts
  const [activeDrafts, setActiveDrafts] = useState(() => getActiveDrafts(projectId));
  const refreshDrafts = () => setActiveDrafts(getActiveDrafts(projectId));

  // Collapsible sections
  const [openSectionOpen, setOpenSectionOpen] = useState(true);
  const [sentSectionOpen, setSentSectionOpen] = useState(false);

  // Pending summaries banner — Supabase Realtime
  const [summariesCount, setSummariesCount] = useState(0);
  useEffect(() => {
    let channel = null;
    let cancelled = false;
    const fetchCount = async () => {
      try {
        if (!window.YBP_SUPABASE) return;
        const sb = await window.YBP_SUPABASE.getClient();
        const { data: { session } } = await sb.auth.getSession();
        if (!session?.user?.id || cancelled) return;
        const { count, error } = await sb
          .from('pending_summaries')
          .select('*', { count: 'exact', head: true })
          .eq('user_id', session.user.id);
        if (!cancelled) setSummariesCount(error ? 0 : (count || 0));
      } catch {}
    };
    const initAndSubscribe = async () => {
      await fetchCount();
      if (!window.YBP_SUPABASE || cancelled) return;
      try {
        const sb = await window.YBP_SUPABASE.getClient();
        const { data: { session } } = await sb.auth.getSession();
        if (!session?.user?.id || cancelled) return;
        channel = sb
          .channel('reports-pending-summaries')
          .on('postgres_changes', {
            event: '*',
            schema: 'public',
            table: 'pending_summaries',
            filter: `user_id=eq.${session.user.id}`,
          }, () => { fetchCount(); })
          .subscribe();
      } catch (e) {
        console.warn('[reports] Realtime summaries failed:', e.message);
      }
    };
    const initTimer = setTimeout(initAndSubscribe, 1500);
    const onApproved = () => fetchCount();
    window.addEventListener('ybp-pending-summary-approved', onApproved);
    return () => {
      cancelled = true;
      clearTimeout(initTimer);
      window.removeEventListener('ybp-pending-summary-approved', onApproved);
      if (channel) { window.YBP_SUPABASE?.getClient?.().then?.(sb => sb.removeChannel(channel)).catch?.(() => {}); }
    };
  }, []);

  // Combine static data.js reports with sync-store reports, filter by project
  const allReports = useMemo(() => {
    const siteReports = (store.reports || []).filter(r => r.projectId === projectId);
    return siteReports.sort((a,b) => (b.date||'').localeCompare(a.date||''));
  }, [store, projectId]);

  const byKind = (k) => allReports.filter(r => r.kind === k);

  const REPORT_TYPES = [
    {
      k: 'daily', label: 'דוח יומי',
      desc: 'סיכום יום באתר — התקדמות, קבלנים, ריג׳קטים',
      color: '#1d4ed8', bg: '#eff6ff',
      count: byKind('daily').length,
      onCreate: onNewDaily,
    },
    {
      k: 'weekly', label: 'דוח שבועי',
      desc: 'אגרגציה אוטומטית של השבוע + מה מתוכנן',
      color: '#7c3aed', bg: '#f3e8ff',
      count: byKind('weekly').length,
      onCreate: onNewWeekly,
    },
    {
      k: 'rejects', label: 'דוח ריג׳קטים',
      desc: 'רק ריג׳קטים — קצר וממוקד',
      color: '#dc2626', bg: '#fee2e2',
      count: byKind('rejects').length,
      onCreate: onNewRejects,
    },
    {
      k: 'infra', label: 'תיעוד תשתיות',
      desc: 'תיעוד שלבי תשתיות עם תמונות — לפי סוג',
      color: '#9333ea', bg: '#fdf4ff',
      count: byKind('infra').length,
      onCreate: onNewInfra,
    },
    {
      k: 'meeting', label: 'סיכום פגישה',
      desc: 'סיכום פגישה, החלטות ומשימות',
      color: '#0891b2', bg: '#ecfeff',
      count: byKind('meeting').length,
      onCreate: onNewMeeting,
    },
    {
      k: 'siteDoc', label: 'תיעוד אתר',
      desc: 'אלבום תמונות עם קטגוריות — תיעוד ויזואלי של האתר',
      color: '#0891b2', bg: '#cffafe',
      count: null,
      onCreate: onOpenSiteDoc,
      badge: 'אלבום',
    },
    {
      k: 'infraSurvey', label: 'סקר תשתיות',
      desc: 'בדיקת תשתיות קיימות בתחילת פרויקט — חשמל, אינסטלציה, מיזוג, מבנה',
      color: '#0891b2', bg: '#cffafe',
      count: null,
      onCreate: onNewInfraSurvey,
      badge: 'פתיחת פרויקט',
    },
  ];

  return (
    <div style={{ minHeight:'100%', background:'#f6f7f9', fontFamily:'Assistant, sans-serif', direction:'rtl' }}>
      {/* Header */}
      <header style={{
        background:'#fff', borderBottom:'1px solid #e5e7eb', padding:'14px 24px',
        display:'flex', alignItems:'center', gap:12, position:'sticky', top:0, zIndex:10,
      }}>
        <button onClick={onBack} style={{
          background:'transparent', border:'none', cursor:'pointer', color:'#6b7280',
          display:'flex', alignItems:'center', gap:4, fontSize:14, padding:6,
        }}>
          <Icon name="chevron" size={18}/> חזרה
        </button>
        <div style={{ width:1, height:24, background:'#e5e7eb' }}/>
        <div style={{ flex:1 }}>
          <div style={{ fontSize:11, color:'#6b7280', fontWeight:600, letterSpacing:0.3 }}>
            {project?.name}
          </div>
          <h1 style={{ margin:0, fontSize:18, fontWeight:700, color:'#1f2937' }}>
            דוחות אתר
          </h1>
        </div>
      </header>

      {/* Pending summaries banner */}
      {summariesCount > 0 && (
        <div style={{
          background: 'linear-gradient(135deg,#f5f3ff,#ede9fe)',
          borderBottom: '1px solid #c4b5fd',
          padding: '10px 24px',
          display: 'flex', alignItems: 'center', gap: 12,
          direction: 'rtl',
        }}>
          <span style={{ fontSize: 20 }}>📋</span>
          <div style={{ flex: 1 }}>
            <span style={{ fontSize: 14, fontWeight: 700, color: '#5b21b6' }}>
              {summariesCount === 1 ? 'סיכום אחד ממתין מקלוד' : `${summariesCount} סיכומים ממתינים מקלוד`}
            </span>
            <span style={{ fontSize: 13, color: '#7c3aed', marginRight: 8 }}>
              — ניתן למלא טופס דוח אוטומטית
            </span>
          </div>
          <button
            onClick={() => window.openPendingSummariesModal && window.openPendingSummariesModal()}
            style={{
              background: '#7c3aed', color: '#fff', border: 'none', borderRadius: 8,
              padding: '8px 16px', cursor: 'pointer', fontSize: 13, fontWeight: 700,
              fontFamily: 'inherit', minHeight: 36,
            }}
          >
            פתח סיכומים
          </button>
        </div>
      )}

      {/* Drafts + Sent — inline sections (no sticky panel) */}

      {/* Create cards */}
      <div style={{ padding:'24px', maxWidth:1100, margin:'0 auto' }}>
        <div style={{ fontSize:13, color:'#6b7280', fontWeight:600, marginBottom:12, letterSpacing:0.3 }}>
          יצירת דוח חדש
        </div>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(280px, 1fr))', gap:14 }}>
          {REPORT_TYPES.map(t => (
            <button key={t.k} onClick={t.onCreate} style={{
              background:'#fff', border:'1px solid #e5e7eb', borderRadius:12,
              padding:20, cursor:'pointer', textAlign:'right', fontFamily:'inherit',
              display:'flex', flexDirection:'column', gap:10, alignItems:'flex-start',
              transition:'all 0.15s',
            }}
            onMouseEnter={e => { e.currentTarget.style.borderColor = t.color; e.currentTarget.style.transform = 'translateY(-2px)'; e.currentTarget.style.boxShadow = '0 8px 20px rgba(0,0,0,0.06)'; }}
            onMouseLeave={e => { e.currentTarget.style.borderColor = '#e5e7eb'; e.currentTarget.style.transform = 'none'; e.currentTarget.style.boxShadow = 'none'; }}
            >
              <div style={{ display:'flex', alignItems:'center', gap:10, width:'100%' }}>
                <div style={{
                  width:40, height:40, borderRadius:10, background:t.bg, color:t.color,
                  display:'flex', alignItems:'center', justifyContent:'center',
                  fontWeight:700, fontSize:13,
                }}>
                  {t.k === 'daily' ? 'D' : t.k === 'weekly' ? 'W' : t.k === 'rejects' ? 'RJ' : t.k === 'infra' ? 'IF' : t.k === 'meeting' ? '🤝' : t.k === 'siteDoc' ? '📸' : 'IS'}
                </div>
                <div style={{ flex:1 }}>
                  <div style={{ display:'flex', alignItems:'center', gap:6 }}>
                    <div style={{ fontSize:16, fontWeight:700, color:'#1f2937' }}>{t.label}</div>
                    {t.badge && (
                      <span style={{
                        fontSize:10, fontWeight:700, padding:'2px 7px', borderRadius:8,
                        background: t.bg, color: t.color, border: `1px solid ${t.color}33`,
                      }}>{t.badge}</span>
                    )}
                  </div>
                  <div style={{ fontSize:11, color:'#9ca3af', marginTop:2 }}>
                    {t.count !== null ? `${t.count} בארכיון` : (t.k === 'siteDoc' ? 'אלבום ויזואלי' : 'דוח חד-פעמי לפתיחת פרויקט')}
                  </div>
                </div>
                <div style={{ color:t.color }}>
                  <Icon name="plus" size={20}/>
                </div>
              </div>
              <div style={{ fontSize:13, color:'#6b7280', lineHeight:1.5 }}>{t.desc}</div>
            </button>
          ))}
        </div>

        {/* Section: פתוחים (drafts) */}
        <div style={{ marginTop:36 }}>
          <button
            onClick={() => setOpenSectionOpen(v => !v)}
            style={{
              display:'flex', alignItems:'center', justifyContent:'space-between',
              width:'100%', background:'none', border:'none', cursor:'pointer',
              padding:'0 0 12px', fontFamily:'inherit', textAlign:'right',
            }}
          >
            <div style={{ display:'flex', alignItems:'center', gap:8 }}>
              <span style={{ fontSize:13, color:'#92400e', fontWeight:700, letterSpacing:0.3 }}>
                📝 פתוחים
              </span>
              {activeDrafts.length > 0 && (
                <span style={{
                  background:'#fbbf24', color:'#78350f', fontWeight:800, fontSize:11,
                  padding:'2px 8px', borderRadius:12,
                }}>{activeDrafts.length}</span>
              )}
            </div>
            <span style={{ fontSize:18, color:'#9ca3af', transform: openSectionOpen ? 'rotate(90deg)' : 'none', transition:'transform 0.15s' }}>›</span>
          </button>

          {openSectionOpen && (
            activeDrafts.length === 0 ? (
              <div style={{
                background:'#fff', border:'1px dashed #e5e7eb', borderRadius:10,
                padding:'24px 20px', textAlign:'center', color:'#9ca3af', fontSize:14,
              }}>
                אין טיוטות פתוחות.
              </div>
            ) : (
              <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
                {activeDrafts.map(d => {
                  const ageMin = d.savedAt ? Math.floor((Date.now() - d.savedAt) / 60000) : null;
                  const ageLabel = ageMin === null ? '' : ageMin < 60 ? `לפני ${ageMin} דק׳` : ageMin < 1440 ? `לפני ${Math.floor(ageMin/60)} שע׳` : `לפני ${Math.floor(ageMin/1440)} ימים`;
                  const onContinue = () => {
                    if (d.kind === 'daily') onNewDaily && onNewDaily();
                    else if (d.kind === 'weekly') onNewWeekly && onNewWeekly();
                    else if (d.kind === 'rejects') onNewRejects && onNewRejects();
                    else if (d.kind === 'infra') onNewInfra && onNewInfra();
                  };
                  const onDelete = () => {
                    if (window.cloudSave) window.cloudSave(d.draftKey, null).catch(() => {});
                    else { try { localStorage.removeItem(d.localKey); } catch {} }
                    refreshDrafts();
                  };
                  return (
                    <div key={d.localKey} style={{
                      background:'#fff', borderRadius:10, border:'1px solid #fde68a',
                      padding:'12px 16px', display:'flex', alignItems:'center', gap:12,
                    }}>
                      <span style={{
                        background: d.kindColor + '18', color: d.kindColor,
                        fontWeight:800, fontSize:11, padding:'3px 8px', borderRadius:6,
                        border:`1px solid ${d.kindColor}33`, whiteSpace:'nowrap',
                      }}>{d.kindLabel}</span>
                      <div style={{ flex:1, minWidth:0 }}>
                        <div style={{ fontSize:14, fontWeight:700, color:'#1f2937', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>
                          {d.projectName}
                        </div>
                        {ageLabel && <div style={{ fontSize:11, color:'#9ca3af' }}>{ageLabel}</div>}
                      </div>
                      <button onClick={onContinue} style={{
                        background:'#1a2c4a', color:'#fff', border:'none', borderRadius:7,
                        padding:'8px 14px', cursor:'pointer', fontWeight:700, fontFamily:'inherit', fontSize:13,
                        whiteSpace:'nowrap', minHeight:36,
                      }}>המשך עריכה</button>
                      <button onClick={onDelete} style={{
                        background:'#fee2e2', color:'#dc2626', border:'none', borderRadius:7,
                        padding:'8px 12px', cursor:'pointer', fontWeight:700, fontFamily:'inherit', fontSize:13,
                        whiteSpace:'nowrap', minHeight:36,
                      }}>מחק</button>
                    </div>
                  );
                })}
              </div>
            )
          )}
        </div>

        {/* Section: נשלחו (sent reports) */}
        <div style={{ marginTop:28 }}>
          <button
            onClick={() => setSentSectionOpen(v => !v)}
            style={{
              display:'flex', alignItems:'center', justifyContent:'space-between',
              width:'100%', background:'none', border:'none', cursor:'pointer',
              padding:'0 0 12px', fontFamily:'inherit', textAlign:'right',
            }}
          >
            <div style={{ display:'flex', alignItems:'center', gap:8 }}>
              <span style={{ fontSize:13, color:'#6b7280', fontWeight:700, letterSpacing:0.3 }}>
                ✅ נשלחו
              </span>
              {allReports.length > 0 && (
                <span style={{
                  background:'#e5e7eb', color:'#374151', fontWeight:700, fontSize:11,
                  padding:'2px 8px', borderRadius:12,
                }}>{allReports.length}</span>
              )}
            </div>
            <span style={{ fontSize:18, color:'#9ca3af', transform: sentSectionOpen ? 'rotate(90deg)' : 'none', transition:'transform 0.15s' }}>›</span>
          </button>

          {sentSectionOpen && (
            allReports.length === 0 ? (
              <div style={{
                background:'#fff', border:'1px dashed #e5e7eb', borderRadius:10,
                padding:'40px 20px', textAlign:'center', color:'#9ca3af', fontSize:14,
              }}>
                עדיין לא נשלחו דוחות. התחל בהוספת דוח יומי.
              </div>
            ) : (
              <div style={{ background:'#fff', border:'1px solid #e5e7eb', borderRadius:10, overflow:'hidden' }}>
                {allReports.map((r, i) => {
                  const type = REPORT_TYPES.find(t => t.k === r.kind);
                  return (
                    <div key={r.id} onClick={() => onOpenReport(r.id)} style={{
                      padding:'14px 18px', borderBottom: i < allReports.length-1 ? '1px solid #f3f4f6' : 'none',
                      display:'flex', alignItems:'center', gap:14, cursor:'pointer',
                      transition:'background 0.1s',
                    }}
                    onMouseEnter={e => e.currentTarget.style.background = '#fafbfc'}
                    onMouseLeave={e => e.currentTarget.style.background = '#fff'}
                    >
                      <div style={{
                        width:36, height:36, borderRadius:8,
                        background: type?.bg || '#f3f4f6', color: type?.color || '#6b7280',
                        display:'flex', alignItems:'center', justifyContent:'center',
                        fontSize:11, fontWeight:700,
                      }}>
                        {r.kind === 'daily' ? 'D' : r.kind === 'weekly' ? 'W' : r.kind === 'rejects' ? 'RJ' : r.kind === 'infra' ? 'IF' : r.kind === 'meeting' ? 'M' : 'IS'}
                      </div>
                      <div style={{ flex:1, minWidth:0 }}>
                        <div style={{ fontSize:14, fontWeight:600, color:'#1f2937', marginBottom:2 }}>
                          {r.title}
                        </div>
                        <div style={{ fontSize:12, color:'#6b7280', display:'flex', gap:10, alignItems:'center' }}>
                          <span style={{ fontFamily:'ui-monospace, Menlo, monospace' }}>{r.id}</span>
                          <span>·</span>
                          <span>{fmtDateHe(r.date)}</span>
                          <span>·</span>
                          <span>{r.author}</span>
                          {r.rejects?.length > 0 && (
                            <>
                              <span>·</span>
                              <span style={{ color:'#dc2626', fontWeight:600 }}>
                                {r.rejects.length} ריג׳קטים
                              </span>
                            </>
                          )}
                        </div>
                      </div>
                      <Icon name="chevronR" size={16} color="#9ca3af"/>
                    </div>
                  );
                })}
              </div>
            )
          )}
        </div>
      </div>
    </div>
  );
};

// ────────────────────────────────────────────────────────────────────
// REJECT CARD (editable) — used inside all 3 forms
// ────────────────────────────────────────────────────────────────────
const RejectCard = ({ reject, idx, contacts, onChange, onRemove }) => {
  const { isMobile } = useViewport();
  const [expanded, setExpanded] = useState(!reject.title);
  const [manualAssignee, setManualAssignee] = useState(!contacts.length || (reject.assigneeId === '__manual__') ? true : false);
  const sev = SEVERITY_OPTS.find(s => s.k === reject.severity) || SEVERITY_OPTS[1];

  // Custom trades from localStorage
  const getCustomTrades = () => {
    try { return JSON.parse(localStorage.getItem('ybp_custom_trades') || '[]'); } catch { return []; }
  };
  const [customTrades, setCustomTrades] = useState(getCustomTrades);
  const allTrades = [...TRADES, ...customTrades.filter(t => !TRADES.includes(t))];

  const addTrade = (t) => {
    if (!t) return;
    const cur = reject.trades || [];
    if (!cur.includes(t)) onChange({ ...reject, trades: [...cur, t] });
  };

  const removeTrade = (t) => {
    onChange({ ...reject, trades: (reject.trades || []).filter(x => x !== t) });
  };

  const addCustomTrade = () => {
    const t = prompt('הכנס שם בעל מקצוע:');
    if (!t || !t.trim()) return;
    const trimmed = t.trim();
    const customs = getCustomTrades();
    if (!customs.includes(trimmed)) {
      const updated = [...customs, trimmed];
      localStorage.setItem('ybp_custom_trades', JSON.stringify(updated));
      setCustomTrades(updated);
    }
    addTrade(trimmed);
  };

  const handlePhoto = (e) => {
    const files = Array.from(e.target.files || []);
    if (!files.length) return;
    files.forEach(f => {
      const img = new Image();
      const url = URL.createObjectURL(f);
      img.onload = () => {
        // Compress: max 1200px wide, quality 0.72 JPEG
        const MAX = 1200;
        const ratio = Math.min(1, MAX / img.width);
        const canvas = document.createElement('canvas');
        canvas.width = Math.round(img.width * ratio);
        canvas.height = Math.round(img.height * ratio);
        canvas.getContext('2d').drawImage(img, 0, 0, canvas.width, canvas.height);
        const compressed = canvas.toDataURL('image/jpeg', 0.72);
        URL.revokeObjectURL(url);
        onChange({ ...reject, photos: [...(reject.photos || (reject.photo ? [reject.photo] : [])), compressed], photo: null });
      };
      img.src = url;
    });
  };

  return (
    <div style={{
      background:'#fff', border:`1px solid ${expanded ? sev.color : '#e5e7eb'}`,
      borderRadius:10, overflow:'hidden',
      boxShadow: expanded ? `0 0 0 3px ${sev.bg}` : 'none',
      transition:'all 0.15s',
    }}>
      {/* Collapsed/Expanded header */}
      <div style={{ display:'flex', alignItems:'center', gap:10, padding:'10px 14px', background:'#fafbfc' }}>
        <div style={{
          width:24, height:24, borderRadius:6, background: sev.bg, color: sev.color,
          fontSize:11, fontWeight:700, display:'flex', alignItems:'center', justifyContent:'center',
        }}>
          {idx + 1}
        </div>
        <input
          value={reject.title || ''}
          onChange={e => onChange({ ...reject, title: e.target.value })}
          placeholder="ממצא ריג'קט — שם הממצא (יופיע בטבלה)"
          style={{
            flex:1, border:'none', background:'transparent', fontSize:14, fontWeight:600,
            color:'#1f2937', fontFamily:'inherit', outline:'none',
          }}
        />
        <button onClick={() => setExpanded(!expanded)} style={{
          background:'transparent', border:'none', cursor:'pointer', color:'#6b7280', padding:4,
          display:'flex', alignItems:'center',
        }}>
          <Icon name={expanded ? 'chevronD' : 'chevron'} size={16}/>
        </button>
        <button onClick={onRemove} style={{
          background:'transparent', border:'none', cursor:'pointer', color:'#dc2626', padding:4,
          display:'flex', alignItems:'center',
        }}>
          <Icon name="close" size={16}/>
        </button>
      </div>

      {expanded && (
        <div style={{ padding:14, display:'flex', flexDirection:'column', gap:12 }}>
          {/* Description */}
          <div>
            <label style={labelSt}>תיאור</label>
            <textarea
              value={reject.description || ''}
              onChange={e => onChange({ ...reject, description: e.target.value })}
              placeholder="פרט מה הבעיה, איפה, ומה צריך לתקן..."
              rows={2}
              style={textareaSt}
            />
          </div>

          {/* Trades — select + chips */}
          <div>
            <label style={labelSt}>תחום / בעל מקצוע</label>
            <div style={{ display:'flex', gap:6, marginBottom:6 }}>
              <select
                value=""
                onChange={e => { if (e.target.value) addTrade(e.target.value); }}
                style={{ ...selectSt, flex:1 }}
              >
                <option value="">+ הוסף תחום...</option>
                {allTrades.filter(t => !(reject.trades || []).includes(t)).map(t => (
                  <option key={t} value={t}>{t}</option>
                ))}
              </select>
              <button type="button" onClick={addCustomTrade} style={{
                padding:'7px 12px', borderRadius:6, border:'1px solid #e5e7eb',
                background:'#f9fafb', color:'#374151', fontSize:12, cursor:'pointer', fontFamily:'inherit', flexShrink:0,
              }}>✏️ ידני</button>
            </div>
            {(reject.trades || []).length > 0 && (
              <div style={{ display:'flex', flexWrap:'wrap', gap:5 }}>
                {(reject.trades || []).map(t => (
                  <span key={t} style={{
                    display:'inline-flex', alignItems:'center', gap:4,
                    padding:'3px 10px', borderRadius:14, fontSize:12, fontWeight:500,
                    background:'#eff6ff', color:'#1d4ed8', border:'1px solid #bfdbfe',
                  }}>
                    {t}
                    <button type="button" onClick={() => removeTrade(t)} style={{
                      background:'none', border:'none', cursor:'pointer', color:'#6b7280', padding:0, fontSize:13, lineHeight:1,
                    }}>×</button>
                  </span>
                ))}
              </div>
            )}
          </div>

          {/* Assignee + Severity row */}
          <div style={{ display:'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap:10 }}>
            <div>
              <label style={labelSt}>אחראי לתיקון</label>
              <select
                value={reject.assigneeId || (reject.assignee ? '__manual__' : '')}
                onChange={e => {
                  const val = e.target.value;
                  if (val === '__manual__') {
                    setManualAssignee(true);
                    onChange({ ...reject, assigneeId: '__manual__', assignee: '' });
                  } else {
                    const c = contacts.find(x => x.id === val);
                    setManualAssignee(false);
                    onChange({ ...reject, assigneeId: val, assignee: c ? c.name : '' });
                  }
                }}
                style={selectSt}
              >
                <option value="">— בחר אחראי —</option>
                {contacts.length > 0 && (
                  <optgroup label="אנשי קשר">
                    {contacts.map(c => (
                      <option key={c.id} value={c.id}>{c.name}{c.role ? ` · ${c.role}` : ''}</option>
                    ))}
                  </optgroup>
                )}
                <option value="__manual__">✏️ הכנסה ידנית...</option>
              </select>
              {(manualAssignee || reject.assigneeId === '__manual__') && (
                <input
                  value={reject.assignee || ''}
                  onChange={e => onChange({ ...reject, assignee: e.target.value })}
                  placeholder="שם האחראי..."
                  style={{ ...inputSt, marginTop:6 }}
                />
              )}
            </div>
            <div>
              <label style={labelSt}>חומרה</label>
              <div style={{ display:'flex', flexWrap:'wrap', gap:4 }}>
                {SEVERITY_OPTS.map(s => (
                  <button key={s.k} type="button" onClick={() => onChange({ ...reject, severity: s.k })} style={{
                    flex:'1 1 45%', padding:'8px 4px', borderRadius:6, fontSize:12, fontWeight:600,
                    border: reject.severity === s.k ? `1px solid ${s.color}` : '1px solid #e5e7eb',
                    background: reject.severity === s.k ? s.bg : '#fff',
                    color: reject.severity === s.k ? s.color : '#6b7280',
                    cursor:'pointer', fontFamily:'inherit',
                  }}>{s.label}</button>
                ))}
              </div>
            </div>
          </div>

          {/* Due date + Photos row */}
          <div style={{ display:'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap:10 }}>
            <div>
              <label style={labelSt}>תאריך יעד</label>
              <div style={{ display:'flex', gap:3, marginBottom:5 }}>
                {[['⚡','היום',0],['📅','מחר',1],['📆','שבוע',7],['📅','חודש',30]].map(([ico,lbl,days]) => {
                  const d = new Date(); d.setDate(d.getDate() + days);
                  const iso = d.toISOString().slice(0,10);
                  const active = reject.due === iso;
                  return (
                    <button key={lbl} type="button" onClick={() => onChange({ ...reject, due: iso })} style={{
                      flex:1, padding:'4px 2px', fontSize:10, borderRadius:5,
                      border: active ? '1px solid #1d4ed8' : '1px solid #e5e7eb',
                      background: active ? '#eff6ff' : '#fff',
                      color: active ? '#1d4ed8' : '#6b7280',
                      cursor:'pointer', fontFamily:'inherit', whiteSpace:'nowrap',
                    }}>{ico} {lbl}</button>
                  );
                })}
              </div>
              <input type="date" value={reject.due || ''}
                onChange={e => onChange({ ...reject, due: e.target.value })}
                style={inputSt}
              />
            </div>
            <div>
              <label style={labelSt}>תמונות ({(reject.photos || (reject.photo ? [reject.photo] : [])).length})</label>
              <div style={{ display:'flex', flexDirection:'column', gap:4, marginBottom:4 }}>
                {(reject.photos || (reject.photo ? [reject.photo] : [])).map((ph, pi) => (
                  <div key={pi} style={{ position:'relative', display:'inline-block' }}>
                    <img src={ph} alt="" style={{ width:'100%', maxWidth:160, height:'auto', display:'block', borderRadius:4, border:'1px solid #d1d5db' }}/>
                    <button type="button" onClick={() => {
                      const cur = reject.photos || (reject.photo ? [reject.photo] : []);
                      onChange({ ...reject, photos: cur.filter((_,j)=>j!==pi), photo: null });
                    }} style={{
                      position:'absolute', top:4, left:4, width:20, height:20,
                      background:'rgba(220,38,38,0.85)', color:'#fff', border:'none', borderRadius:10,
                      fontSize:12, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', lineHeight:1,
                    }}>×</button>
                  </div>
                ))}
                <PhotoPickerInline onFiles={files => handlePhoto({ target: { files } })} multiple/>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// Shared input styles
const labelSt = { display:'block', fontSize:11, fontWeight:600, color:'#6b7280', marginBottom:5, letterSpacing:0.2 };
const inputSt = { width:'100%', padding:'9px 10px', borderRadius:6, border:'1px solid #e5e7eb', fontSize:13, fontFamily:'inherit', background:'#fff', color:'#1f2937', outline:'none', boxSizing:'border-box' };
const textareaSt = { ...inputSt, resize:'vertical', minHeight:60 };
const selectSt = { ...inputSt, cursor:'pointer' };

// Make these globally available for other report forms
window.ReportsHub = ReportsHub;
window.RejectCard = RejectCard;
window.YBP_TRADES = TRADES;
window.YBP_SEVERITY = SEVERITY_OPTS;
window.YBP_DAY_STATUS = DAY_STATUS_OPTS;
window.ybpLabelSt = labelSt;
window.ybpInputSt = inputSt;
window.ybpTextareaSt = textareaSt;
window.ybpSelectSt = selectSt;
window.fmtDateHe = fmtDateHe;
window.todayISO = todayISO;

})();
