// Rejects Report Form — דוח ריג'קטים (v2, based on daily-report pattern)
(function(){
const { useState, useEffect, useMemo, useRef } = React;

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

const TRADE_OPTS = [
  'גמרים','אינסטלציה','חשמל','צבע','טיח','ריצוף','נגרות','מסגרות',
  'מיזוג אוויר','אלומיניום','גבס','חפירה','איטום','שיש','ריהוט',
];

// ── RejectViewCard (read-only) ────────────────────────────────────────────────
const RejectViewCard = ({ r, idx, onDelete, onEdit }) => {
  const sev = SEVERITY_OPTS.find(s => s.k === r.severity) || SEVERITY_OPTS[2];
  const photos = r.photos || (r.photo ? [r.photo] : []);
  return (
    <div style={{
      background:'#fff', border:`1px solid ${sev.color}`,
      borderRadius:10, overflow:'hidden',
      boxShadow:`0 0 0 3px ${sev.bg}`,
    }}>
      <div style={{ display:'flex', alignItems:'center', gap:10, padding:'10px 14px', background:'#fafbfc', borderBottom:`1px solid ${sev.bg}` }}>
        <div style={{
          width:24, height:24, borderRadius:6, background:sev.bg, color:sev.color,
          fontSize:11, fontWeight:700, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0,
        }}>{idx+1}</div>
        <span style={{ flex:1, fontSize:14, fontWeight:700, color:'#1f2937' }}>{r.title || 'ריג׳קט ללא כותרת'}</span>
        <span style={{ padding:'3px 10px', borderRadius:10, fontSize:10, fontWeight:700, background:sev.bg, color:sev.color, flexShrink:0 }}>{sev.label}</span>
        {r.source === 'direct' && (
          <>
            <span style={{ padding:'2px 7px', borderRadius:8, fontSize:10, background:'#f0fdf4', color:'#16a34a', fontWeight:600, flexShrink:0 }}>ישיר</span>
            {onEdit && (
              <button onClick={() => onEdit(r)} style={{ background:'transparent', border:'none', cursor:'pointer', color:'#6b7280', padding:4, display:'flex', alignItems:'center' }}
                title="ערוך">✏️</button>
            )}
            <button onClick={onDelete} style={{ background:'transparent', border:'none', cursor:'pointer', color:'#dc2626', padding:4, display:'flex', alignItems:'center' }}
              title="מחק">✕</button>
          </>
        )}
        {r.source === 'report' && (
          <span style={{ padding:'2px 7px', borderRadius:8, fontSize:10, background:'#eff6ff', color:'#1d4ed8', fontWeight:600, flexShrink:0 }}>מדוח יומי</span>
        )}
      </div>
      <div style={{ padding:'12px 14px', display:'flex', flexDirection:'column', gap:10 }}>
        {r.description && (
          <div style={{ fontSize:12.5, color:'#4b5563', lineHeight:1.5 }}>{r.description}</div>
        )}
        {(r.trades || []).length > 0 && (
          <div style={{ display:'flex', flexWrap:'wrap', gap:5 }}>
            {r.trades.map(t => (
              <span key={t} style={{ padding:'4px 10px', borderRadius:14, fontSize:11, fontWeight:500, background:'#eff6ff', color:'#1d4ed8', border:'1px solid #dbeafe' }}>{t}</span>
            ))}
          </div>
        )}
        <div style={{ display:'flex', flexWrap:'wrap', gap:14, fontSize:11.5, color:'#6b7280' }}>
          {r.assignee && <span>👤 <strong style={{ color:'#1f2937' }}>{r.assignee}</strong></span>}
          {r.due && <span>📅 יעד: <strong style={{ color:'#1a2c4a' }}>{fmtDateHe(r.due)}</strong></span>}
          {(r.reportDate || r.createdAt) && (
            <span style={{ color:'#9ca3af' }}>ממצא: {fmtDateHe(r.reportDate || r.createdAt)}</span>
          )}
        </div>
        {photos.length > 0 && (
          <div style={{ display:'flex', flexWrap:'wrap', gap:6 }}>
            {photos.map((ph, pi) => (
              <img key={pi} src={ph} alt={`תמונה ${pi+1}`}
                style={{ width:80, height:80, objectFit:'cover', borderRadius:6, border:'1px solid #e5e7eb' }}/>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

// ── AddRejectModal (bottom-sheet) ─────────────────────────────────────────────
const AddRejectModal = ({ projectId, projectName, onClose, onAdded, initialData, editId }) => {
  const isEdit = !!editId;
  const contacts = useMemo(() => {
    try {
      const global = JSON.parse(localStorage.getItem('ybp_contacts_v1') || '[]');
      const projIds = (JSON.parse(localStorage.getItem('ybp_proj_contacts_v2') || '{}'))[projectId] || [];
      const proj = global.filter(c => projIds.includes(c.id));
      if (proj.length) return proj;
    } catch {}
    return [];
  }, [projectId]);

  const defaultDue = new Date(Date.now() + 7*24*60*60*1000).toISOString().slice(0,10);
  const [reject, setReject] = useState(() => ({
    id: initialData?.id || `r-${Date.now()}`,
    title: initialData?.title || '',
    description: initialData?.description || '',
    trades: initialData?.trades || [],
    assigneeId: initialData?.assigneeId || '',
    assignee: initialData?.assignee || '',
    severity: initialData?.severity || 'medium',
    due: initialData?.due || defaultDue,
    photos: initialData?.photos || [],
    source: 'direct',
    projectId,
  }));

  const [noPhotoWarning, setNoPhotoWarning] = useState(false);
  const [submitting, setSubmitting] = useState(false);

  const handleSubmit = async () => {
    if (submitting) return;
    if (!reject.title?.trim()) return;
    if ((reject.photos || []).length === 0 && !noPhotoWarning) {
      setNoPhotoWarning(true);
      return;
    }
    setSubmitting(true);
    try {
      if (isEdit) {
        await SyncStore.updateDirectReject(editId, { ...reject, projectName });
      } else {
        await SyncStore.addDirectReject(projectId, { ...reject, projectName });
      }
      onAdded();
      onClose();
    } finally {
      setSubmitting(false);
    }
  };

  const canSave = !!reject.title?.trim();

  return (
    <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.6)', zIndex:9999, display:'flex', alignItems:'flex-end', justifyContent:'center' }}
      onClick={e => { if (e.target === e.currentTarget) onClose(); }}>
      <div style={{ background:'#f6f7f9', borderRadius:'14px 14px 0 0', width:'100%', maxWidth:640, maxHeight:'92vh', overflow:'auto', direction:'rtl', fontFamily:'Assistant,sans-serif' }}>

        {/* Header */}
        <div style={{ padding:'14px 16px', background:'#fff', borderBottom:'1px solid #e5e7eb', display:'flex', alignItems:'center', justifyContent:'space-between', position:'sticky', top:0, zIndex:2 }}>
          <span style={{ fontSize:15, fontWeight:700, color:'#1f2937' }}>{isEdit ? "עריכת ריג'קט" : "הוספת ריג'קט חדש"}</span>
          <button onClick={onClose} style={{ background:'transparent', border:'none', cursor:'pointer', fontSize:20, color:'#6b7280', lineHeight:1 }}>✕</button>
        </div>

        {/* RejectCard — same UI as daily/weekly reports */}
        <div style={{ padding:16 }}>
          {typeof RejectCard !== 'undefined' ? (
            <RejectCard
              reject={reject}
              idx={0}
              contacts={contacts}
              onChange={setReject}
              onRemove={onClose}
            />
          ) : (
            <div style={{ padding:20, textAlign:'center', color:'#6b7280' }}>טוען...</div>
          )}
        </div>

        {/* Contractor quick-assign */}
        <div style={{ padding:'0 16px 14px' }}>
          <div style={{ fontSize:11, fontWeight:700, color:'#6b7280', marginBottom:6 }}>קבלן אחראי לתיקון:</div>
          {contacts.length > 0 ? (
            <select
              value={reject.assigneeId || ''}
              onChange={e => {
                const c = contacts.find(x => x.id === e.target.value);
                setReject(prev => ({ ...prev, assigneeId: e.target.value, assignee: c ? c.name : '' }));
              }}
              style={{ width:'100%', padding:'9px 10px', borderRadius:6, border:'1px solid #e5e7eb', fontSize:13, fontFamily:'inherit', background:'#fff', boxSizing:'border-box' }}
            >
              <option value="">— בחר מאנשי קשר —</option>
              {contacts.map(c => (
                <option key={c.id} value={c.id}>{c.name}{c.role ? ` · ${c.role}` : ''}</option>
              ))}
            </select>
          ) : (
            <select
              value={reject.assignee || ''}
              onChange={e => setReject(prev => ({ ...prev, assignee: e.target.value, assigneeId: '' }))}
              style={{ width:'100%', padding:'9px 10px', borderRadius:6, border:'1px solid #e5e7eb', fontSize:13, fontFamily:'inherit', background:'#fff', boxSizing:'border-box' }}
            >
              <option value="">— בחר סוג קבלן —</option>
              {TRADE_OPTS.map(t => <option key={t} value={t}>{t}</option>)}
            </select>
          )}
        </div>

        {/* No-photo warning */}
        {noPhotoWarning && (
          <div style={{ margin:'0 16px 8px', padding:'10px 14px', background:'#fef3c7', border:'1px solid #fbbf24', borderRadius:8, fontSize:13, color:'#92400e', display:'flex', alignItems:'center', gap:10 }}>
            <span style={{ fontSize:18 }}>📷</span>
            <div style={{ flex:1 }}>לא הוספת תמונות לריג׳קט. מומלץ לצלם תמונה לתיעוד.</div>
            <button onClick={() => setNoPhotoWarning(false)} style={{ background:'transparent', border:'none', cursor:'pointer', color:'#92400e', fontSize:12, fontWeight:700, fontFamily:'inherit', padding:0, flexShrink:0 }}>הוסף תמונה</button>
          </div>
        )}

        {/* Footer */}
        <div style={{ padding:'12px 16px', background:'#fff', borderTop:'1px solid #e5e7eb', display:'flex', gap:10, position:'sticky', bottom:0, zIndex:2 }}>
          <button onClick={handleSubmit} disabled={!canSave || submitting} style={{
            flex:1, padding:'12px', borderRadius:8, border:'none',
            background: (canSave && !submitting) ? '#1a2c4a' : '#e5e7eb',
            color: (canSave && !submitting) ? '#fff' : '#9ca3af',
            fontSize:14, fontWeight:700, cursor: (canSave && !submitting) ? 'pointer' : 'default', fontFamily:'inherit',
          }}>{submitting ? 'מעלה תמונות...' : isEdit ? "שמור שינויים" : noPhotoWarning ? "המשך בלי תמונה" : "הוסף ריג'קט"}</button>
          <button onClick={onClose} style={{
            padding:'12px 16px', borderRadius:8, border:'1px solid #e5e7eb',
            background:'#fff', color:'#6b7280', fontSize:14, cursor:'pointer', fontFamily:'inherit',
          }}>ביטול</button>
        </div>
      </div>
    </div>
  );
};

// ── Main: RejectsReportForm ───────────────────────────────────────────────────
const RejectsReportForm = ({ projectId, editReportId, prefillData, onBack, onAfterSubmit }) => {
  const { isMobile, isLandscape } = useViewport();
  const project = YBP_DATA.projects.find(p => p.id === projectId);
  const contacts = useMemo(() => {
    try {
      const global = JSON.parse(localStorage.getItem('ybp_contacts_v1') || '[]');
      const projIds = (JSON.parse(localStorage.getItem('ybp_proj_contacts_v2') || '{}'))[projectId] || [];
      const proj = global.filter(c => projIds.includes(c.id));
      if (proj.length) return proj;
      if (global.length) return global;
    } catch {}
    return YBP_DATA.projectDetail?.contacts || [];
  }, [projectId]);
  const user = (window.YBP_AUTH && window.YBP_AUTH.getCurrentUser) ? window.YBP_AUTH.getCurrentUser() : YBP_DATA.user;

  const editReport = editReportId ? (SyncStore.get().reports || []).find(r => r.id === editReportId) : null;
  const ec = editReport?.content || {};

  const nextId = useMemo(() => SyncStore.peekNextReportId(projectId, 'rejects'), [projectId]);

  // SyncStore subscription (for directRejects)
  const [storeData, setStoreData] = useState(() => SyncStore.get());
  useEffect(() => SyncStore.subscribe(setStoreData), []);

  const [date, setDate] = useState(editReport?.date || todayISO());
  const [notes, setNotes] = useState(() => {
    if (ec.notes) return ec.notes;
    if (editReportId || !prefillData) return '';
    const aiRejects = Array.isArray(prefillData.structured?.rejects) ? prefillData.structured.rejects : [];
    return prefillData.structured?.notes || (aiRejects.length > 0 ? '' : (prefillData.summaryText || ''));
  });
  const [rejects, setRejects] = useState(() => {
    if (editReport?.rejects) return editReport.rejects;
    if (!editReportId && prefillData) {
      const aiRejects = Array.isArray(prefillData.structured?.rejects) ? prefillData.structured.rejects : [];
      const source = aiRejects.length ? aiRejects : (prefillData.suggestedRejects || []);
      if (source.length) {
        return source.map((r, i) => ({
          id: `r-pf-${Date.now()}-${i}`,
          title: r.title || '',
          description: r.description || '',
          trades: r.trades || [],
          assigneeId: '',
          assignee: r.assignee || '',
          severity: r.severity || 'medium',
          due: r.due || defaultDueDate(),
          photo: null,
        }));
      }
    }
    return [];
  });

  const [showAddModal, setShowAddModal] = useState(false);
  const [editingReject, setEditingReject] = useState(null);
  const [submittedReport, setSubmittedReport] = useState(null);
  const [cloudSaveStatus, setCloudSaveStatus] = useState(null); // null | 'saved' | 'pending'
  const [submitting, setSubmitting] = useState(false);

  // directRejects from SyncStore (added via AddRejectModal)
  const directRejects = (storeData.directRejects || [])
    .filter(r => r.projectId === projectId)
    .map(r => ({ ...r, source: 'direct' }));

  // ── Voice fill listener ───────────────────────────────────────────────────
  useEffect(() => {
    const handler = (e) => {
      const { formType, data } = e.detail || {};
      if (formType !== 'rejects' || !data) return;
      if (data.notes) setNotes(data.notes);
      if (data.rejectTitle) {
        setRejects(prev => [...prev, {
          id: `r-voice-${Date.now()}`,
          title: data.rejectTitle,
          description: data.rejectDescription || '',
          trades: [],
          assigneeId: '',
          assignee: data.rejectAssignee || '',
          severity: 'medium',
          due: data.rejectDue || defaultDueDate(),
          photo: null,
        }]);
      }
    };
    window.addEventListener('ybp-voice-fill', handler);
    return () => window.removeEventListener('ybp-voice-fill', handler);
  }, []);

  // Rejects handlers
  const addReject = () => setRejects(r => [...r, {
    id: `r-${Date.now()}`, title:'', description:'', trades:[], assigneeId:'',
    severity:'medium', due: defaultDueDate(), photo: null,
  }]);
  const updateReject = (id, data) => setRejects(r => r.map(x => x.id === id ? data : x));
  const removeReject = (id) => setRejects(r => r.filter(x => x.id !== id));

  // ── Draft / auto-save ────────────────────────────────────────────────────
  const userId = useMemo(() => {
    try { return JSON.parse(localStorage.getItem('ybp_auth_session') || '{}')?.email || 'unknown'; } catch { return 'unknown'; }
  }, []);
  const draftKey = `ybp_draft_rejects_${projectId}_${userId}`;
  const [lastDraftSavedAt, setLastDraftSavedAt] = useState(null);
  const [cloudSavedAt, setCloudSavedAt] = useState(null);
  const [isDirty, setIsDirty] = useState(false);
  const [draftTick, setDraftTick] = useState(0);
  const autoSaveTimer       = useRef(null);
  const isFirstRender       = useRef(true);
  const restorePromptShown  = useRef(false);

  // סמן טופס פעיל — מונע force-update בזמן עריכה
  useEffect(() => {
    window.YBP_FORM_DIRTY = true;
    window.YBP_CURRENT_SCREEN = 'rejects-report';
    return () => { window.YBP_FORM_DIRTY = false; window.YBP_FORM_STATE_SNAPSHOT = null; };
  }, []);

  // minute ticker — refreshes age label
  useEffect(() => {
    const t = setInterval(() => setDraftTick(n => n + 1), 60000);
    return () => clearInterval(t);
  }, []);

  function formatDraftAge(savedAt) {
    const ms  = Date.now() - savedAt;
    const min = Math.floor(ms / 60000);
    if (min < 1)  return 'לפני פחות מדקה';
    if (min < 60) return `לפני ${min} דקות`;
    const hr = Math.floor(min / 60);
    if (hr < 24)  return `לפני ${hr} שעות`;
    const day = Math.floor(hr / 24);
    return `לפני ${day} ${day === 1 ? 'יום' : 'ימים'}`;
  }

  // שחזור טיוטה בעלייה (רק אם לא edit ולא prefill)
  useEffect(() => {
    if (editReportId || prefillData) return;
    if (restorePromptShown.current) return;
    restorePromptShown.current = true;
    (async () => {
      // סנכרן מ-Supabase לפני טעינה מ-localStorage (cross-device)
      try {
        const cloudResult = await window.loadDraftFromSupabase?.({ kind: 'rejects', projectId });
        if (cloudResult?.formData?.savedAt) {
          const localDraft = cloudLoadSync(draftKey, null);
          if ((cloudResult.formData.savedAt || 0) > (localDraft?.savedAt || 0)) {
            await cloudSave(draftKey, cloudResult.formData);
          }
        }
      } catch (_) {}
      const draft = await cloudLoad(draftKey);
      if (!draft?.savedAt) return;
      const ageLabel = formatDraftAge(draft.savedAt);
      const doLoad = () => {
        if (draft.date !== undefined)  setDate(draft.date);
        if (draft.notes !== undefined) setNotes(draft.notes);
        if (draft.rejects)             setRejects(draft.rejects);
        setLastDraftSavedAt(draft.savedAt);
      };
      if (typeof window.confirmDialog === 'function') {
        window.confirmDialog({
          title: 'יש טיוטה ממתינה',
          message: `נשמרה ${ageLabel}. להמשיך עריכה?`,
          confirmText: 'המשך עריכה',
          cancelText: 'התחל מחדש',
          onConfirm: doLoad,
          onCancel: () => cloudSave(draftKey, null),
        });
      } else if (window.confirm(`יש טיוטה שנשמרה ${ageLabel}. להמשיך עריכה?`)) {
        doLoad();
      } else {
        cloudSave(draftKey, null);
      }
    })();
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  // isDirty — מסמן שינוי בכל שדה
  useEffect(() => {
    if (isFirstRender.current) { isFirstRender.current = false; return; }
    setIsDirty(true);
  }, [date, notes, rejects]);

  // snapshot לemergency save — מתעדכן בכל render
  useEffect(() => {
    window.YBP_FORM_STATE_SNAPSHOT = { projectId, date, notes, rejects };
  });

  // auto-save — debounce 30 שניות
  useEffect(() => {
    if (!isDirty) return;
    if (autoSaveTimer.current) clearTimeout(autoSaveTimer.current);
    autoSaveTimer.current = setTimeout(async () => {
      const now = Date.now();
      const formData = { date, notes, rejects, savedAt: now };
      await cloudSave(draftKey, formData);
      window.upsertDraftReport?.({ draftKey, kind: 'rejects', projectId, reportDate: date, formData }).catch(() => {});
      setLastDraftSavedAt(now);
      setCloudSavedAt(now);
      setIsDirty(false);
    }, 30000);
    return () => { if (autoSaveTimer.current) clearTimeout(autoSaveTimer.current); };
  }, [isDirty, date, notes, rejects]); // eslint-disable-line

  const handleSaveDraft = async () => {
    const now = Date.now();
    const formData = { date, notes, rejects, savedAt: now };
    await cloudSave(draftKey, formData);
    window.upsertDraftReport?.({ draftKey, kind: 'rejects', projectId, reportDate: date, formData }).catch(() => {});
    setLastDraftSavedAt(now);
    setCloudSavedAt(now);
    setIsDirty(false);
    if (typeof window.toastSuccess === 'function') window.toastSuccess('טיוטה נשמרה');
  };

  const handleForceCloudSave = async () => {
    const now = Date.now();
    const formData = { date, notes, rejects, savedAt: now };
    await cloudSave(draftKey, formData);
    window.upsertDraftReport?.({ draftKey, kind: 'rejects', projectId, reportDate: date, formData }).catch(() => {});
    setLastDraftSavedAt(now);
    setCloudSavedAt(now);
    if (typeof window.toastSuccess === 'function') window.toastSuccess('נשמר ב-cloud ✓');
  };

  const handleDeleteDraft = async () => {
    if (!window.confirm('למחוק את הטיוטה ולצאת? פעולה זו לא ניתנת לביטול.')) return;
    try {
      if (typeof YBP_AUTH !== 'undefined' && YBP_AUTH.appendAuditEvent) {
        const session = YBP_AUTH.getSession();
        const snapshot = { kind: 'rejects', projectId, date, notes, rejects };
        YBP_AUTH.appendAuditEvent({
          action: 'delete-draft',
          actor: session?.name || 'מנהל',
          detail: `מחק טיוטת דוח ריג'קטים לפרויקט ${projectId}`,
          snapshot: JSON.stringify(snapshot),
        });
      }
    } catch (e) { console.warn('[deleteDraft] audit log:', e); }
    try {
      if (window.cloudSave) await window.cloudSave(draftKey, null);
      localStorage.removeItem(draftKey);
    } catch (e) { console.warn('[deleteDraft] cloudSave/localStorage:', e); }
    if (editReportId && window.deleteReportFromSupabase) {
      try { await window.deleteReportFromSupabase(editReportId); }
      catch (e) { console.warn('[deleteDraft] Supabase delete:', e); }
    }
    if (typeof window.toastSuccess === 'function') window.toastSuccess('הטיוטה נמחקה');
    onBack && onBack();
  };

  // ── PDF ──────────────────────────────────────────────────────────────────
  const buildPdfParts = () => {
    const fmtD2 = iso => { if (!iso) return '—'; const d = new Date(iso + 'T00:00:00'); return String(d.getDate()).padStart(2,'0')+'/'+String(d.getMonth()+1).padStart(2,'0')+'/'+d.getFullYear(); };
    const dateStr = fmtD2(date);
    const tmpId = nextId || 'טיוטה';
    const allForPdf = [...rejects, ...directRejects];
    const rejectsHtml = allForPdf.length
      ? `<div class="sec"><div class="sec-lbl">ריג'קטים (${allForPdf.length})</div><table class="d"><thead><tr><th>#</th><th>ממצא</th><th>תיאור</th><th>חומרה</th><th>אחראי</th><th>יעד</th></tr></thead><tbody>${
          allForPdf.map((r,i) => {
            const sev = SEVERITY_OPTS.find(s => s.k === r.severity) || SEVERITY_OPTS[2];
            return `<tr class="reject-card"><td style="text-align:center;font-weight:700">${i+1}</td><td style="font-weight:600">${r.title||'—'}</td><td style="font-size:10px;color:#4b5563">${r.description||'—'}</td><td style="font-size:10px;color:${sev.color};font-weight:700">${sev.label}</td><td style="font-size:10px">${r.assignee||'—'}</td><td style="font-weight:600;font-size:10px;color:#1a2c4a">${fmtD2(r.due)}</td></tr>`;
          }).join('')
        }</tbody></table></div>`
      : '';
    const notesHtml = notes ? `<div class="sec"><div class="sec-lbl">הערות</div><div style="font-size:11.5px;color:#374151;line-height:1.6;white-space:pre-wrap">${notes}</div></div>` : '';
    const headerMetaHtml = `<div class="mb"><div><span class="badge" style="background:#fee2e2;color:#dc2626;border:1px solid #fca5a5">REJECTS REPORT — DRAFT</span></div><div style="text-align:left"><div style="font-family:ui-monospace,Menlo,monospace;font-size:13px;font-weight:700;color:#1a2c4a">${tmpId}</div><div style="font-size:11px;color:#9ca3af;margin-top:2px">${dateStr}</div></div></div><div class="sec" style="padding-bottom:8px"><h2 style="font-size:22px;font-weight:700;color:#dc2626;line-height:1.2;margin-bottom:6px">דוח ריג'קטים — ${dateStr}</h2>${project?.name?`<div style="font-size:13px;color:#6b7280">פרויקט: <strong style="color:#1f2937">${project.name}</strong>${project.address?' · '+project.address:''}</div>`:''}</div><div class="sec" style="display:grid;grid-template-columns:repeat(3,1fr);gap:12px;padding:12px;background:#fee2e2;border-radius:4px;border:1px solid #fca5a5"><div style="text-align:center"><div style="font-size:10px;color:#6b7280;font-weight:700;margin-bottom:3px">תאריך</div><div style="font-size:12px;font-weight:600;color:#1f2937">${dateStr}</div></div><div style="text-align:center"><div style="font-size:10px;color:#6b7280;font-weight:700;margin-bottom:3px">נוצר על ידי</div><div style="font-size:12px;font-weight:600;color:#1f2937">${user?.name||''}</div></div><div style="text-align:center"><div style="font-size:10px;color:#dc2626;font-weight:700;margin-bottom:3px">ריג'קטים</div><div style="font-size:12px;font-weight:600;color:#dc2626">${allForPdf.length} פתוחים</div></div></div>`;
    const bodyHtml = [rejectsHtml, notesHtml].join('');
    return { headerMetaHtml, bodyHtml };
  };

  const handlePreviewPdf = () => {
    if (typeof window.YBPPdf === 'undefined') { alert('מודול PDF לא טעון'); return; }
    const { headerMetaHtml, bodyHtml } = buildPdfParts();
    const logoSrc = document.querySelector('img[alt="YBP"]')?.src || '';
    const fmtD2 = iso => { if (!iso) return ''; const d = new Date(iso+'T00:00:00'); return String(d.getDate()).padStart(2,'0')+'-'+String(d.getMonth()+1).padStart(2,'0')+'-'+d.getFullYear(); };
    window.YBPPdf.generatePdf({ orientation:'portrait', logoSrc, fileName:`${fmtD2(date)}_${project?.name||''}_ריג'קטים_טיוטה`, headerMetaHtml, bodyHtml, sigHtml:'', projectId, uploadToDrive: false });
  };

  const handlePrint = () => {
    if (typeof window.YBPPdf === 'undefined') { alert('מודול PDF לא טעון'); return; }
    const { headerMetaHtml, bodyHtml } = buildPdfParts();
    const logoSrc = document.querySelector('img[alt="YBP"]')?.src || '';
    const fmtD2 = iso => { if (!iso) return ''; const d = new Date(iso+'T00:00:00'); return String(d.getDate()).padStart(2,'0')+'-'+String(d.getMonth()+1).padStart(2,'0')+'-'+d.getFullYear(); };
    window.YBPPdf.openPrintWindow({ orientation:'portrait', logoSrc, fileName:`${fmtD2(date)}_${project?.name||''}_ריג'קטים_טיוטה`, headerMetaHtml, bodyHtml, sigHtml:'' });
  };

  // ── Submit ────────────────────────────────────────────────────────────────
  const handleSubmit = async () => {
    if (submitting) return;
    const allRejects = [...rejects, ...directRejects];
    if (allRejects.length === 0) {
      if (window.toastError) window.toastError('אין ריג׳קטים לכלול בדוח — הוסף לפחות אחד');
      return;
    }
    setSubmitting(true);
    try {
      const reportId = editReport ? editReport.id : SyncStore.nextReportId(projectId, 'rejects');
      const report = {
        id: reportId,
        projectId,
        kind: 'rejects',
        title: `דוח ריג'קטים — ${fmtDateHe(date)}`,
        date,
        author: (user.name || '').split(' ')[0] || user.name,   // v78 — שם ראשון בלבד
        content: { notes, totalRejects: allRejects.length },
        rejects: allRejects,
      };
      await SyncStore.submitSiteReport(report);
      // מחק directRejects שנכנסו לדוח
      allRejects
        .filter(r => r.source === 'direct' || r.source === 'pending_summary')
        .forEach(r => SyncStore.deleteDirectReject(r.id));
      if (prefillData?.summaryId) {
        window.PendingSummariesAPI?.approveUsed(prefillData.summaryId);
      }
      // שמור ל-Supabase — הצעד הקריטי
      const saveResult = window.saveReportAsSent
        ? await window.saveReportAsSent(draftKey, report)
        : { ok: false, error: 'saveReportAsSent not available' };
      // נקה טיוטה גם אם הענן נכשל (הדוח קיים ב-localStorage)
      cloudSave(draftKey, null);
      setCloudSaveStatus(saveResult.ok ? 'saved' : 'pending');
      setSubmittedReport(report);
      // לא קוראים onBack — מציגים פאנל הצלחה
    } catch (e) {
      console.error('[RejectsReport] handleSubmit error:', e);
      if (window.toastError) window.toastError('שגיאה בשמירת הדוח');
    } finally {
      setSubmitting(false);
    }
  };

  const allRejectsCount = rejects.length + directRejects.length;
  const tabBarH = isMobile ? (isLandscape ? 48 : 60) : 0;
  const actionBarH = 64;

  return (
    <div style={{ minHeight:'100%', background:'#f6f7f9', fontFamily:'Assistant, sans-serif', direction:'rtl', paddingBottom: tabBarH + actionBarH + 16 }}>
      {/* TODO(photos): פיצ'ר הוספת תמונות אחרי דוח הוסר ב-v3.9.0.41 — צריך לתכנן מחדש זרימת תמונות→Drive. */}

      {/* Add / Edit modals */}
      {showAddModal && (
        <AddRejectModal
          projectId={projectId}
          projectName={project?.name}
          onClose={() => setShowAddModal(false)}
          onAdded={() => setStoreData(SyncStore.get())}
        />
      )}
      {editingReject && (
        <AddRejectModal
          projectId={projectId}
          projectName={project?.name}
          initialData={editingReject}
          editId={editingReject.id}
          onClose={() => setEditingReject(null)}
          onAdded={() => { setStoreData(SyncStore.get()); setEditingReject(null); }}
        />
      )}

      {/* Header */}
      <header style={{
        background:'#fff', borderBottom:'1px solid #e5e7eb', padding:'12px 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, fontFamily:'inherit',
        }}>
          <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 }}>
            {project?.name} · <span style={{ fontFamily:'ui-monospace, Menlo, monospace', color:'#dc2626' }}>{nextId}</span>
          </div>
          <div style={{ display:'flex', alignItems:'center', gap:8 }}>
            <h1 style={{ margin:0, fontSize:17, fontWeight:700, color:'#1f2937' }}>
              {editReport ? "עריכת דוח ריג'קטים" : "דוח ריג'קטים חדש"}
            </h1>
            {cloudSavedAt && Date.now() - cloudSavedAt < 300000 ? (
              <span style={{ fontSize:11, color:'#10b981', fontWeight:600 }}>
                ☁️ נשמר ב-cloud {formatDraftAge(cloudSavedAt)} {draftTick > -1 ? '' : ''}
              </span>
            ) : lastDraftSavedAt ? (
              <span style={{ fontSize:11, color:'#f59e0b', fontWeight:600 }}>
                📱 נשמר במכשיר ·{' '}
                <button onClick={handleForceCloudSave} style={{ background:'none', border:'none', color:'#1a2c4a', fontWeight:700, cursor:'pointer', fontFamily:'inherit', fontSize:11, padding:0 }}>
                  שמור ב-cloud
                </button>
                {draftTick > -1 ? '' : ''}
              </span>
            ) : isDirty ? (
              <span style={{ fontSize:11, color:'#ef4444', fontWeight:600 }}>● לא נשמר</span>
            ) : null}
          </div>
        </div>
      </header>

      {/* Toolbar */}
      <div style={{
        background:'#fff', borderBottom:'1px solid #e5e7eb',
        padding: isMobile ? '8px 12px' : '8px 24px',
        display:'flex', gap:8, flexWrap:'wrap',
      }}>
        {[
          { label:'שמור טיוטה', icon:'💾', onClick: handleSaveDraft },
          { label:'תצוגת PDF',  icon:'👁️', onClick: handlePreviewPdf },
          { label:'הדפס',       icon:'🖨️', onClick: handlePrint },
        ].map(({ label, icon, onClick }) => (
          <button key={label} onClick={onClick} style={{
            flex: isMobile ? '1 1 calc(33% - 6px)' : '0 0 auto',
            minHeight:44, padding:'8px 14px',
            borderRadius:8, border:'1px solid #e5e7eb', background:'#fafbfc',
            color:'#374151', fontSize:13, fontWeight:600,
            cursor:'pointer', fontFamily:'inherit',
            display:'flex', alignItems:'center', justifyContent:'center', gap:6,
          }}>
            <span style={{ fontSize:16 }}>{icon}</span>
            {label}
          </button>
        ))}
      </div>

      {/* Form */}
      <div style={{ maxWidth:820, margin:'0 auto', padding: isMobile ? '12px 14px' : '20px 24px', display:'flex', flexDirection:'column', gap:16 }}>

        {/* Date */}
        <Section title="פרטי הדוח">
          <div style={{ display:'grid', gridTemplateColumns: isMobile ? '1fr' : '180px 1fr', gap:12 }}>
            <div>
              <label style={ybpLabelSt}>תאריך</label>
              <input type="date" value={date} onChange={e => setDate(e.target.value)} style={ybpInputSt}/>
            </div>
            <div style={{ display:'flex', alignItems:'flex-end' }}>
              <div style={{ padding:'10px 14px', background:'#fef2f2', border:'1px solid #fca5a5', borderRadius:8, fontSize:12, color:'#dc2626', fontWeight:600 }}>
                📋 כל הממצאים הפתוחים יאוחדו בדוח זה
              </div>
            </div>
          </div>
        </Section>

        {/* Rejects section */}
        <Section title="ריג׳קטים" subtitle="ריג׳קטים שנוספו לדוח זה. כל ריג'קט שיישלח יהפוך למשימה עם אחראי ותאריך יעד.">
          <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
            {/* Inline rejects — editable via RejectCard */}
            {rejects.map((r, i) => (
              <RejectCard key={r.id} reject={r} idx={i} contacts={contacts}
                onChange={data => updateReject(r.id, data)}
                onRemove={() => removeReject(r.id)}
              />
            ))}
            {/* directRejects from SyncStore — read-only via RejectViewCard */}
            {directRejects.map((r, i) => (
              <RejectViewCard
                key={r.id || i}
                r={r}
                idx={rejects.length + i}
                onEdit={reject => setEditingReject(reject)}
                onDelete={() => {
                  if (window.confirm("מחק ריג'קט זה?")) {
                    SyncStore.deleteDirectReject(r.id);
                    setStoreData(SyncStore.get());
                  }
                }}
              />
            ))}
            {/* Add buttons */}
            <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
              <button onClick={addReject} style={{
                flex:'1 1 160px', padding:'12px', borderRadius:8, border:'1px dashed #cbd5e1', background:'#fff',
                color:'#475569', fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:'inherit',
                display:'flex', alignItems:'center', justifyContent:'center', gap:6,
              }}>
                <Icon name="plus" size={16}/> הוסף ריג׳קט
              </button>
              <button onClick={() => setShowAddModal(true)} style={{
                flex:'1 1 160px', padding:'12px', borderRadius:8, border:'1px dashed #dc2626', background:'#fff',
                color:'#dc2626', fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:'inherit',
                display:'flex', alignItems:'center', justifyContent:'center', gap:6,
              }}>
                📷 הוסף עם תמונה
              </button>
            </div>
          </div>
        </Section>

        {/* Notes */}
        <Section title="הערות">
          <textarea value={notes} onChange={e => setNotes(e.target.value)}
            placeholder="הערות כלליות, דרישות לקבלנים, הנחיות לטיפול..."
            rows={3} style={ybpTextareaSt}
          />
        </Section>

        {/* Auto signature */}
        <div style={{
          background:'#f9fafb', border:'1px solid #f3f4f6', borderRadius:8, padding:'12px 14px',
          display:'flex', alignItems:'center', gap:12,
        }}>
          {user.signatureImage
            ? <img src={user.signatureImage} alt="חתימה" style={{ height:40, maxWidth:160, objectFit:'contain' }}/>
            : <Icon name="check" size={14} color="#10b981"/>
          }
          <span style={{ fontSize:12, color:'#6b7280' }}>
            ייחתם אוטומטית: <strong style={{ color:'#1f2937' }}>{user.name}</strong> · {user.role} · {fmtDateHe(date)}
          </span>
        </div>
      </div>

      {/* Action bar */}
      <div style={{
        position:'sticky', bottom:0, background:'#fff',
        borderTop:'1px solid #e5e7eb', padding: isMobile ? '10px 14px' : '12px 24px', zIndex:800,
        display:'flex', alignItems:'center', gap:12, justifyContent:'space-between',
        marginTop:16,
      }}>
        <div style={{ fontSize:12, color:'#6b7280' }}>
          {allRejectsCount > 0 && <span>{allRejectsCount} ריג׳קטים בדוח</span>}
        </div>
        <div style={{ display:'flex', gap:10 }}>
          <button onClick={handleDeleteDraft} style={{
            padding:'9px 14px', borderRadius:6,
            border:'1px solid var(--ybp-danger-bg,#fecaca)',
            background:'var(--ybp-panel,#fff)', color:'var(--ybp-danger,#dc2626)',
            fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:'inherit',
            display:'flex', alignItems:'center', gap:6,
          }}>🗑 מחק טיוטה</button>
          <button onClick={onBack} style={{
            padding:'9px 18px', borderRadius:6, border:'1px solid #e5e7eb', background:'#fff',
            color:'#6b7280', fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:'inherit',
          }}>ביטול</button>
          <button onClick={handleSubmit} disabled={submitting} style={{
            padding:'9px 18px', borderRadius:6, border:'none',
            background: submitting ? '#9ca3af' : '#dc2626',
            color:'#fff', fontSize:13, fontWeight:700,
            cursor: submitting ? 'not-allowed' : 'pointer', fontFamily:'inherit',
            display:'flex', alignItems:'center', gap:6,
          }}>
            <Icon name="send" size={14}/> {submitting ? 'מפיק דוח...' : 'הפק דוח'}
          </button>
        </div>
      </div>

      {/* פאנל הצלחה — מופיע אחרי הפקת דוח */}
      {submittedReport && (
        <div style={{
          position: 'fixed', bottom: tabBarH, left: 0, right: 0,
          background: '#fff', borderTop: '2px solid #e5e7eb',
          borderRadius: '16px 16px 0 0',
          boxShadow: '0 -8px 32px rgba(0,0,0,0.12)',
          padding: '20px 16px 24px', zIndex: 50,
          direction: 'rtl', fontFamily: 'Assistant, sans-serif',
        }}>
          <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:16 }}>
            <div style={{
              width: 40, height: 40, borderRadius: '50%',
              background: cloudSaveStatus === 'saved' ? '#dcfce7' : '#fef3c7',
              display:'flex', alignItems:'center', justifyContent:'center', fontSize:20, flexShrink:0
            }}>
              {cloudSaveStatus === 'saved' ? '✓' : '⏳'}
            </div>
            <div>
              <div style={{ fontSize:16, fontWeight:700, color:'#1f2937' }}>
                {cloudSaveStatus === 'saved' ? 'הדוח הופק ונשמר ✓' : 'הדוח הופק'}
              </div>
              <div style={{ fontSize:12, color: cloudSaveStatus === 'saved' ? '#16a34a' : '#d97706' }}>
                {cloudSaveStatus === 'saved'
                  ? 'נשמר בענן בהצלחה'
                  : '⚠️ ממתין לחיבור — נשמר במכשיר'}
              </div>
            </div>
          </div>

          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:8, marginBottom:12 }}>
            {[
              { icon:'📄', label:'הורד PDF', action: () => {
                if (window.generateReportPDF) window.generateReportPDF(submittedReport);
                else if (window.toastInfo) window.toastInfo('PDF בהכנה...');
              }},
              { icon:'💬', label:'WhatsApp', action: () => {
                const text = `דוח ריג'קטים — ${submittedReport.title || ''}\nפרויקט: ${submittedReport.projectId}\nתאריך: ${submittedReport.date}`;
                window.open(`https://wa.me/?text=${encodeURIComponent(text)}`, '_blank');
              }},
              { icon:'✉️', label:'מייל', action: () => {
                const subj = encodeURIComponent(submittedReport.title || "דוח ריג'קטים");
                const body = encodeURIComponent(`דוח ריג'קטים — ${submittedReport.date}`);
                window.open(`https://mail.google.com/mail/?view=cm&su=${subj}&body=${body}`, '_blank');
              }},
            ].map(({ icon, label, action }) => (
              <button key={label} onClick={action} style={{
                padding:'12px 4px', borderRadius:10, border:'1px solid #e5e7eb',
                background:'#f9fafb', cursor:'pointer', fontFamily:'inherit',
                display:'flex', flexDirection:'column', alignItems:'center', gap:4,
              }}>
                <span style={{ fontSize:22 }}>{icon}</span>
                <span style={{ fontSize:11, fontWeight:600, color:'#374151' }}>{label}</span>
              </button>
            ))}
          </div>

          <button onClick={() => { setSubmittedReport(null); onAfterSubmit ? onAfterSubmit(submittedReport) : onBack(); }}
            style={{
              width:'100%', padding:'12px', borderRadius:10, border:'none',
              background:'#1a2c4a', color:'#fff', fontSize:14, fontWeight:700,
              cursor:'pointer', fontFamily:'inherit',
            }}>
            סיום וחזרה לפרויקט
          </button>
        </div>
      )}
    </div>
  );
};

// ── Section wrapper ───────────────────────────────────────────────────────────
const Section = ({ title, subtitle, children }) => (
  <div style={{
    background:'#fff', border:'1px solid #e5e7eb', borderRadius:10, padding:18,
  }}>
    <div style={{ marginBottom: subtitle ? 4 : 12 }}>
      <h3 style={{ margin:0, fontSize:14, fontWeight:700, color:'#1f2937' }}>{title}</h3>
      {subtitle && <div style={{ fontSize:12, color:'#9ca3af', marginTop:2 }}>{subtitle}</div>}
    </div>
    <div style={{ marginTop: subtitle ? 14 : 0 }}>{children}</div>
  </div>
);

const iconBtnSt = {
  background:'#fff', border:'1px solid #e5e7eb', borderRadius:6, cursor:'pointer',
  color:'#dc2626', display:'flex', alignItems:'center', justifyContent:'center',
};

window.RejectsReportForm = RejectsReportForm;
})();
