// Weekly Report Form — אגרגציה של דוחות יומיים + סיכום שבועי
(function(){
const { useState, useEffect, useMemo } = React;

// ── Gantt helpers (inline — no dependency on GanttScreen scope) ───────────────
const addDaysLocal = (iso, n) => {
  if (!iso) return iso;
  const d = new Date(iso + 'T00:00:00');
  d.setDate(d.getDate() + n);
  return d.toISOString().slice(0, 10);
};
const todayISOLocal = () => new Date().toISOString().slice(0, 10);

// Returns tasks + booklet phases for a project
const getGanttItems = (projectId, store) => {
  const items = [];
  (store.tasks || []).filter(t => t.projectId === projectId && t.status !== 'archived').forEach(t => {
    const start = t.startDate || t.createdAt?.slice(0, 10) || todayISOLocal();
    const end = t.due || addDaysLocal(start, 7);
    if (!start || !end) return;
    items.push({
      id: 'task_' + t.id,
      name: t.title || 'משימה',
      start, end,
      status: t.status || 'open',
      type: 'task',
      assignee: t.assignee || '',
      percentDone: t.percentDone || 0,
    });
  });
  const project = (window.YBP_DATA?.projects || []).find(p => p.id === projectId);
  (project?.phases || []).forEach((ph, pi) => {
    const start = ph.startDate || project.startDate || todayISOLocal();
    const end = ph.endDate || ph.dueDate || addDaysLocal(start, 14);
    if (!start || !end) return;
    items.push({
      id: 'bk_' + pi,
      name: ph.name || ph.title || 'שלב ' + (pi + 1),
      start, end,
      status: ph.status || 'ממתין',
      type: 'booklet',
      assignee: '',
      percentDone: ph.percentDone || 0,
    });
  });
  return items;
};

// Check if an item is active during a date range
const itemOverlaps = (item, rangeStart, rangeEnd) =>
  item.start <= rangeEnd && item.end >= rangeStart;

const STATUS_HE = {
  done:'הסתיים', הסתיים:'הסתיים', אושר:'אושר',
  in_progress:'בעבודה', בעבודה:'בעבודה',
  open:'פתוח', פתוח:'פתוח',
  ממתין:'ממתין', 'ממתין לאישור':'ממתין לאישור',
  תקוע:'תקוע',
};
const STATUS_COLOR = {
  done:'#27AE60', הסתיים:'#27AE60', אושר:'#27AE60',
  in_progress:'#4A90D9', בעבודה:'#4A90D9',
  open:'#F0A500', פתוח:'#F0A500', ממתין:'#95A5A6',
  תקוע:'#E74C3C',
};
const fmtD = 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();
};

// ── Previous Weekly Report Card ───────────────────────────────────────────────
const PrevWeeklyCard = ({ report }) => {
  const [open, setOpen] = useState(false);
  const c = report.content || {};
  return (
    <div style={{
      border: '1px solid #e5e7eb', borderRadius: 8, overflow: 'hidden',
      background: '#fff', marginBottom: 8,
    }}>
      <div
        onClick={() => setOpen(o => !o)}
        style={{
          padding: '10px 14px', display: 'flex', alignItems: 'center', gap: 10,
          cursor: 'pointer', userSelect: 'none',
        }}
      >
        <span style={{ fontSize: 13, fontWeight: 700, color: '#1f2937', flex: 1 }}>{report.title}</span>
        <span style={{ fontSize: 11, color: '#6b7280' }}>{fmtD(report.date)}</span>
        <span style={{
          padding: '2px 8px', borderRadius: 10, fontSize: 10, fontWeight: 700,
          background: '#f3e8ff', color: '#7c3aed',
        }}>שבועי</span>
        <span style={{ fontSize: 14, color: '#9ca3af', transform: open ? 'rotate(90deg)' : 'none', transition: 'transform 0.15s' }}>▶</span>
      </div>
      {open && (
        <div style={{ padding: '0 14px 14px', borderTop: '1px solid #f3f4f6' }}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 8, marginTop: 10, marginBottom: 10 }}>
            {[
              { label: 'ימי עבודה', v: c.totalWorkDays ?? '—' },
              { label: 'עיכובים', v: c.delayDays ?? '—' },
              { label: "ריג'קטים", v: report.rejects?.length ?? '—' },
            ].map(({ label, v }) => (
              <div key={label} style={{
                background: '#f9fafb', borderRadius: 6, padding: '8px 10px', textAlign: 'center',
                border: '1px solid #e5e7eb',
              }}>
                <div style={{ fontSize: 20, fontWeight: 800, color: '#1a2c4a' }}>{v}</div>
                <div style={{ fontSize: 10, color: '#9ca3af', marginTop: 2 }}>{label}</div>
              </div>
            ))}
          </div>
          {c.summary && (
            <div style={{ fontSize: 12, color: '#374151', background: '#f9fafb', borderRadius: 6, padding: '8px 10px', marginBottom: 6, lineHeight: 1.6 }}>
              <strong style={{ color: '#6b7280', display: 'block', marginBottom: 3, fontSize: 11 }}>סיכום:</strong>
              {c.summary}
            </div>
          )}
          {c.nextWeek && (
            <div style={{ fontSize: 12, color: '#374151', background: '#eff6ff', borderRadius: 6, padding: '8px 10px', lineHeight: 1.6 }}>
              <strong style={{ color: '#1d4ed8', display: 'block', marginBottom: 3, fontSize: 11 }}>תחזית ששויכה:</strong>
              {c.nextWeek}
            </div>
          )}
        </div>
      )}
    </div>
  );
};

// ── Gantt Forecast Section ────────────────────────────────────────────────────
const GanttForecast = ({ items, nextStart, nextEnd, onAutoFill }) => {
  const active = items.filter(i => itemOverlaps(i, nextStart, nextEnd) &&
    i.status !== 'done' && i.status !== 'הסתיים' && i.status !== 'אושר');

  if (active.length === 0) return (
    <div style={{ fontSize: 12, color: '#9ca3af', textAlign: 'center', padding: '16px 0' }}>
      לא נמצאו משימות/שלבים פעילים בשבוע הבא בגאנט
    </div>
  );

  const buildText = () => active.map(i => {
    const typeLabel = i.type === 'booklet' ? 'שלב' : 'משימה';
    const statusLabel = STATUS_HE[i.status] || i.status;
    const parts = [`• ${i.name} (${typeLabel}, ${statusLabel})`];
    if (i.assignee) parts.push(` — ${i.assignee}`);
    parts.push(` | ${fmtD(i.start)}–${fmtD(i.end)}`);
    if (i.percentDone > 0) parts.push(` | ${i.percentDone}% הושלם`);
    return parts.join('');
  }).join('\n');

  return (
    <div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 12 }}>
        {active.map(item => (
          <div key={item.id} style={{
            display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px',
            background: '#f9fafb', borderRadius: 7, border: '1px solid #e5e7eb',
          }}>
            <div style={{
              width: 8, height: 8, borderRadius: '50%', flexShrink: 0,
              background: STATUS_COLOR[item.status] || '#95a5a6',
            }}/>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: '#1f2937' }}>{item.name}</div>
              <div style={{ fontSize: 10, color: '#9ca3af', marginTop: 1 }}>
                {item.type === 'booklet' ? 'שלב' : 'משימה'} · {fmtD(item.start)} – {fmtD(item.end)}
                {item.assignee ? ` · ${item.assignee}` : ''}
              </div>
            </div>
            {item.percentDone > 0 && (
              <div style={{ fontSize: 10, color: '#6b7280', whiteSpace: 'nowrap' }}>{item.percentDone}%</div>
            )}
            <span style={{
              padding: '2px 7px', borderRadius: 10, fontSize: 10, fontWeight: 600,
              background: (STATUS_COLOR[item.status] || '#95a5a6') + '22',
              color: STATUS_COLOR[item.status] || '#6b7280',
            }}>{STATUS_HE[item.status] || item.status}</span>
          </div>
        ))}
      </div>
      <button onClick={() => onAutoFill(buildText())} style={{
        padding: '7px 14px', borderRadius: 6, border: '1px solid #1a2c4a',
        background: '#1a2c4a', color: '#fff', fontSize: 12, fontWeight: 700,
        cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 6,
      }}>
        ✦ מלא אוטומטית בתחזית
      </button>
    </div>
  );
};

// ── Draft age helper ──────────────────────────────────────────────────────────
function formatDraftAge(savedAt) {
  if (!savedAt) return '';
  const diff = Math.floor((Date.now() - savedAt) / 60000);
  if (diff < 1) return 'לפני פחות מדקה';
  if (diff < 60) return `לפני ${diff} דקות`;
  const h = Math.floor(diff / 60);
  if (h < 24) return `לפני ${h} שעות`;
  return `לפני ${Math.floor(h / 24)} ימים`;
}

// ── Main Form ─────────────────────────────────────────────────────────────────
const WeeklyReportForm = ({ projectId, editReportId, prefillData, onBack, onAfterSubmit }) => {
  const [store, setStore] = useState(SyncStore.get());
  useEffect(() => SyncStore.subscribe(setStore), []);
  const { isMobile } = useViewport();
  const [submittedReport, setSubmittedReport] = useState(null);
  const [cloudSaveStatus, setCloudSaveStatus] = useState(null); // null | 'saved' | 'pending'
  const [printOrientation, setPrintOrientation] = useState('portrait');

  const project = (window.YBP_DATA?.projects || []).find(p => p.id === projectId) || (window.YBP_DATA?.projects || [])[0];

  // Load edit report if editing
  const editReport = editReportId ? (store.reports || []).find(r => r.id === editReportId) : null;
  const ec = editReport?.content || {};

  // Date range
  const now = new Date();
  const weekAgo = new Date(now - 7 * 24 * 60 * 60 * 1000);
  const today = now.toISOString().slice(0, 10);
  const [weekStart, setWeekStart] = useState(ec.weekStart || weekAgo.toISOString().slice(0, 10));
  const [weekEnd, setWeekEnd] = useState(ec.weekEnd || today);

  // Next week range
  const nextStart = addDaysLocal(weekEnd, 1);
  const nextEnd = addDaysLocal(weekEnd, 7);

  // ── Daily reports aggregation (re-runs when weekStart/weekEnd change) ────────
  const { dailyReports, allContractors, allRejects, allIssues, totalWorkDays, delayDays } = useMemo(() => {
    const daily = (store.reports || []).filter(r =>
      r.projectId === projectId && r.kind === 'daily' &&
      r.date >= weekStart && r.date <= weekEnd
    );
    const contractors = {};
    const rejects = [];
    const issues = [];
    let workDays = 0, dDelay = 0;
    daily.forEach(r => {
      const c = r.content || {};
      if (c.dayStatus === 'full') workDays++;
      if (c.dayStatus === 'delay') { workDays++; dDelay++; }
      (c.contractors || []).forEach(co => {
        if (!contractors[co.trade]) contractors[co.trade] = 0;
        contractors[co.trade] += co.count ? +co.count : 1;
      });
      (r.rejects || []).forEach(rj => rejects.push(rj));
      if (c.issues) issues.push({ date: r.date, text: c.issues });
    });
    return { dailyReports: daily, allContractors: contractors, allRejects: rejects, allIssues: issues, totalWorkDays: workDays, delayDays: dDelay };
  }, [store, projectId, weekStart, weekEnd]);

  // ── Previous weekly reports that overlap with selected range ─────────────────
  const prevWeeklyReports = useMemo(() => (store.reports || []).filter(r =>
    r.projectId === projectId && r.kind === 'weekly' &&
    r.content?.weekStart && r.content?.weekEnd &&
    r.content.weekStart <= weekEnd && r.content.weekEnd >= weekStart
  ).sort((a, b) => b.date.localeCompare(a.date)), [store, projectId, weekStart, weekEnd]);

  // ── Gantt items ──────────────────────────────────────────────────────────────
  const ganttItems = useMemo(() => getGanttItems(projectId, store), [store, projectId]);

  // ── Draft auto-save ──────────────────────────────────────────────────────────
  const draftKey           = `ybp_draft_weekly_${projectId}`;
  const [showDraftBanner, setShowDraftBanner] = useState(false);
  const [draftSavedAt, setDraftSavedAt]       = useState(null);
  const restorePromptShown = React.useRef(false);

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

  // ── Form fields ──────────────────────────────────────────────────────────────
  const [summary, setSummary] = useState(() => {
    const base = ec.summary || (!editReportId && prefillData ? (prefillData.structured?.summary || prefillData.summaryText || '') : '');
    if (base) return base;
    try {
      // תמיכה גם במפתח cloudSave (ybp_cloud_) וגם בישן
      const cloud = window.cloudLoadSync ? window.cloudLoadSync(draftKey) : null;
      if (cloud?.summary) return cloud.summary;
      const d = JSON.parse(localStorage.getItem(draftKey) || 'null');
      return d?.summary || '';
    } catch { return ''; }
  });
  const [nextWeek, setNextWeek] = useState(() => {
    const base = ec.nextWeek || (!editReportId && prefillData ? prefillData.structured?.nextWeekFocus || '' : '');
    if (base) return base;
    try {
      const cloud = window.cloudLoadSync ? window.cloudLoadSync(draftKey) : null;
      if (cloud?.nextWeek) return cloud.nextWeek;
      const d = JSON.parse(localStorage.getItem(draftKey) || 'null');
      return d?.nextWeek || '';
    } catch { return ''; }
  });
  const [highlights, setHighlights] = useState(() => {
    const base = ec.highlights || (!editReportId && prefillData ? prefillData.structured?.keyPoints?.join('\n') || '' : '');
    if (base) return base;
    try {
      const cloud = window.cloudLoadSync ? window.cloudLoadSync(draftKey) : null;
      if (cloud?.highlights) return cloud.highlights;
      const d = JSON.parse(localStorage.getItem(draftKey) || 'null');
      return d?.highlights || '';
    } catch { return ''; }
  });
  const [submitting, setSubmitting] = useState(false);
  const [aiLoadingHighlights, setAiLoadingHighlights] = useState(false);
  const [aiLoadingSummary, setAiLoadingSummary] = useState(false);
  const [aiLoadingNextWeek, setAiLoadingNextWeek] = useState(false);
  const [aiLoadingAll, setAiLoadingAll] = useState(false);

  // Check if there's a saved draft to restore (also syncs from Supabase for cross-device)
  useEffect(() => {
    if (restorePromptShown.current) return;
    restorePromptShown.current = true;
    (async () => {
      try {
        const cloudResult = await window.loadDraftFromSupabase?.({ kind: 'weekly', projectId });
        if (cloudResult?.formData?.savedAt) {
          const local = window.cloudLoadSync ? window.cloudLoadSync(draftKey) : null;
          if ((cloudResult.formData.savedAt || 0) > (local?.savedAt || 0)) {
            await window.cloudSave?.(draftKey, cloudResult.formData);
          }
        }
      } catch (_) {}
      const cloud = window.cloudLoadSync ? window.cloudLoadSync(draftKey) : null;
      const d = cloud || null;
      if (d && d.savedAt && !(summary || nextWeek || highlights)) {
        setDraftSavedAt(d.savedAt);
        setShowDraftBanner(true);
      }
    })();
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

  // Auto-save draft every 30s — cloudSave + upsert to Supabase reports
  useEffect(() => {
    if (editReportId) return;
    const id = setInterval(() => {
      const formData = { summary, nextWeek, highlights, savedAt: Date.now() };
      if (window.cloudSave) {
        window.cloudSave(draftKey, formData).catch(() => {});
        window.upsertDraftReport?.({ draftKey, kind: 'weekly', projectId, formData }).catch(() => {});
      } else {
        try { localStorage.setItem(draftKey, JSON.stringify(formData)); } catch (_) {}
      }
    }, 30000);
    return () => clearInterval(id);
  }, [summary, nextWeek, highlights]); // eslint-disable-line react-hooks/exhaustive-deps

  const buildDailyContext = () => {
    if (dailyReports.length === 0) return null;
    const lines = dailyReports.map(r => {
      const c = r.content || {};
      const parts = [`תאריך: ${fmtD(r.date)}`];
      if (c.dayStatus) parts.push(`סטטוס יום: ${c.dayStatus}`);
      if (c.contractors?.length) parts.push(`קבלנים: ${c.contractors.map(x => x.trade + (x.count ? ' ×' + x.count : '')).join(', ')}`);
      if (c.progress) parts.push(`התקדמות: ${c.progress}`);
      if (c.issues) parts.push(`בעיות: ${c.issues}`);
      if (c.notes) parts.push(`הערות: ${c.notes}`);
      if (r.rejects?.length) parts.push(`ריג'קטים: ${r.rejects.map(x => x.title).join(', ')}`);
      return parts.join(' | ');
    }).join('\n');
    return `פרויקט: ${project?.name || ''} | טווח: ${fmtD(weekStart)}–${fmtD(weekEnd)}\n\nדוחות יומיים:\n${lines}`;
  };

  const generateHighlights = async () => {
    const ctx = buildDailyContext();
    if (!ctx) return;
    setAiLoadingHighlights(true);
    try {
      const text = await window.claude.complete({
        messages: [{ role: 'user', content: `אתה עוזר למנהל פרויקטים בבנייה. בהתבסס על הדוחות היומיים הבאים, כתוב 3-5 נקודות בולטות השבוע בעברית. כל נקודה בשורה חדשה שמתחילה ב-•. בלי כותרות, רק הנקודות.\n\n${ctx}` }],
      });
      setHighlights(text.trim());
    } catch(e) { console.error(e); }
    setAiLoadingHighlights(false);
  };

  const generateSummary = async () => {
    const ctx = buildDailyContext();
    if (!ctx) return;
    setAiLoadingSummary(true);
    try {
      const text = await window.claude.complete({
        messages: [{ role: 'user', content: `אתה עוזר למנהל פרויקטים בבנייה. בהתבסס על הדוחות היומיים הבאים, כתוב סיכום שבועי קצר ומקצועי בעברית (3-4 משפטים). כלול: מצב כללי, ימי עבודה, התקדמות, ובעיות עיקריות אם יש.\n\n${ctx}` }],
      });
      setSummary(text.trim());
    } catch(e) { console.error(e); }
    setAiLoadingSummary(false);
  };

  const generateNextWeek = async () => {
    setAiLoadingNextWeek(true);
    try {
      const activeGantt = ganttItems.filter(i =>
        itemOverlaps(i, nextStart, nextEnd) &&
        i.status !== 'done' && i.status !== 'הסתיים' && i.status !== 'אושר'
      );
      const ganttCtx = activeGantt.length
        ? `משימות/שלבים מתוכננים לשבוע הבא (${fmtD(nextStart)}–${fmtD(nextEnd)}):\n` +
          activeGantt.map(i => `• ${i.name} (${i.type === 'booklet' ? 'שלב' : 'משימה'}, ${STATUS_HE[i.status] || i.status}${i.assignee ? ', אחראי: ' + i.assignee : ''}, ${fmtD(i.start)}–${fmtD(i.end)}${i.percentDone > 0 ? ', ' + i.percentDone + '% הושלם' : ''})`).join('\n')
        : 'לא נמצאו פריטים בגאנט לשבוע הבא.';
      const dailyCtx = buildDailyContext() || 'אין דוחות יומיים.';
      const text = await window.claude.complete({
        messages: [{ role: 'user', content: `אתה עוזר למנהל פרויקטים בבנייה. כתוב תחזית שבועית מקצועית בעברית לשבוע הבא, בהתבסס על:\n1. נתוני הגאנט\n2. המשך מהשבוע הנוכחי\n\nכתוב 3-5 נקודות עם •, קצר ומעשי.\n\n${ganttCtx}\n\n${dailyCtx}` }],
      });
      setNextWeek(text.trim());
    } catch(e) { console.error(e); }
    setAiLoadingNextWeek(false);
  };

  const generateAll = async () => {
    if (dailyReports.length === 0 && ganttItems.length === 0) return;
    setAiLoadingAll(true);
    await Promise.all([
      generateHighlights(),
      generateSummary(),
      generateNextWeek(),
    ]);
    setAiLoadingAll(false);
  };

  const handleDeleteDraft = async () => {
    if (!window.confirm('למחוק את הטיוטה ולצאת? פעולה זו לא ניתנת לביטול.')) return;
    try {
      if (typeof YBP_AUTH !== 'undefined' && YBP_AUTH.appendAuditEvent) {
        const session = YBP_AUTH.getSession();
        const snapshot = { kind: 'weekly', projectId, weekStart, weekEnd, editorContent: ec };
        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();
  };

  const handleSubmit = async () => {
    if (submitting) return;
    setSubmitting(true);
    try {
      const id = editReport ? editReport.id : SyncStore.nextReportId(projectId, 'weekly');
      const report = {
        id, kind: 'weekly', projectId,
        title: `דוח שבועי — ${fmtD(weekStart)} עד ${fmtD(weekEnd)}`,
        date: today, author: ((((window.YBP_AUTH && window.YBP_AUTH.getCurrentUser) ? window.YBP_AUTH.getCurrentUser().name : (YBP_DATA.user && YBP_DATA.user.name)) || '').split(' ')[0]) || '',   // v78 — שם ראשון בלבד
        content: {
          weekStart, weekEnd, totalWorkDays, delayDays,
          contractors: Object.entries(allContractors).map(([trade, days]) => ({ trade, days })),
          issues: allIssues, summary, nextWeek, highlights,
          dailyCount: dailyReports.length,
        },
        rejects: allRejects,
      };
      await SyncStore.submitSiteReport(report);
      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)
      if (window.cloudSave) window.cloudSave(draftKey, null).catch(() => {});
      else { try { localStorage.removeItem(draftKey); } catch (_) {} }
      setCloudSaveStatus(saveResult.ok ? 'saved' : 'pending');
      setSubmittedReport(report);
      // לא קוראים onBack — מציגים פאנל הצלחה
    } catch (e) {
      console.error('[Weekly] handleSubmit error:', e);
      if (window.toastError) window.toastError('שגיאה ביצירת הדוח');
    } finally {
      setSubmitting(false);
    }
  };

  const inputSt = {
    width: '100%', padding: '10px 12px', borderRadius: 6, border: '1px solid #e5e7eb',
    fontSize: 13, fontFamily: 'Assistant, sans-serif', outline: 'none', direction: 'rtl',
    boxSizing: 'border-box', background: '#fff',
  };
  const labelSt = { fontSize: 12, fontWeight: 700, color: '#374151', marginBottom: 6, display: 'block' };
  const cardSt = {
    background: '#fff', border: '1px solid #e5e7eb', borderRadius: 10,
    padding: 20, marginBottom: 16,
  };

  return (
    <div style={{ minHeight: '100%', background: '#f6f7f9', fontFamily: 'Assistant, sans-serif', direction: 'rtl' }}>
      {/* TODO(photos): פיצ'ר הוספת תמונות אחרי דוח הוסר ב-v3.9.0.41 — צריך לתכנן מחדש זרימת תמונות→Drive. */}
      {/* Header */}
      <header style={{
        background: '#fff', borderBottom: '1px solid #e5e7eb', padding: '12px 20px',
        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' }}/>
        <span style={{ fontSize: 15, fontWeight: 700, color: '#1f2937' }}>{editReport ? 'עריכת דוח שבועי' : 'דוח שבועי'}</span>
        <span style={{
          padding: '3px 10px', borderRadius: 12, fontSize: 11, fontWeight: 700,
          background: '#f3e8ff', color: '#7c3aed',
        }}>שבועי</span>
        <div style={{ flex: 1 }}/>
        {/* כיוון הדפסה */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 4, background: '#f3f4f6', borderRadius: 6, padding: '3px 6px' }}>
          <span style={{ fontSize: 11, color: '#6b7280', marginLeft: 4 }}>כיוון:</span>
          {[['portrait', '📄 לאורך'], ['landscape', '📋 לרוחב']].map(([val, label]) => (
            <button key={val} onClick={() => setPrintOrientation(val)} style={{
              padding: '4px 9px', borderRadius: 5, border: 'none', fontSize: 11, fontWeight: 600,
              cursor: 'pointer', fontFamily: 'inherit',
              background: printOrientation === val ? '#1a2c4a' : 'transparent',
              color: printOrientation === val ? '#fff' : '#6b7280',
            }}>{label}</button>
          ))}
        </div>
        <button onClick={() => {
          const logoSrc = (() => {
            const el = document.querySelector('img[alt="YBP"]');
            if (el?.src && el.src.includes('ybp-logo')) return el.src;
            const base = window.location.href.replace(/\/[^/]*$/, '');
            return base + '/assets/ybp-logo-new.png';
          })();
          const contractorsHtml = Object.entries(allContractors).length
            ? `<div class="sec"><div class="sec-lbl">קבלנים פעילים השבוע</div><div style="display:flex;flex-wrap:wrap;gap:5px">${Object.entries(allContractors).map(([t,d]) => '<span style="padding:4px 10px;border-radius:12px;background:#eff6ff;color:#1d4ed8;font-size:11px;font-weight:600;border:1px solid #dbeafe">' + t + ' <span style="opacity:0.6">(' + d + ' ימים)</span></span>').join('')}</div></div>` : '';
          const issuesHtml = allIssues.length
            ? `<div class="sec"><div class="sec-lbl">בעיות שעלו השבוע</div>${allIssues.map(iss => '<div style="padding:8px 10px;background:#fef3c7;border-right:3px solid #d97706;border-radius:4px;font-size:11px;color:#713f12;margin-bottom:4px"><strong>' + fmtD(iss.date) + ':</strong> ' + iss.text + '</div>').join('')}</div>` : '';
          const highlightsHtml = highlights ? `<div class="sec"><div class="sec-lbl">נקודות בולטות</div><div style="font-size:11.5px;color:#374151;line-height:1.6;white-space:pre-wrap">${highlights}</div></div>` : '';
          const summaryHtml = summary ? `<div class="sec"><div class="sec-lbl">סיכום שבוע</div><div style="font-size:11.5px;color:#374151;line-height:1.6;white-space:pre-wrap">${summary}</div></div>` : '';
          const nextWeekHtml = nextWeek ? `<div class="sec"><div class="sec-lbl">תחזית שבוע הבא</div><div style="font-size:11.5px;color:#374151;line-height:1.6;white-space:pre-wrap">${nextWeek}</div></div>` : '';
          const rejectsHtml = allRejects.length
            ? `<div class="sec"><div class="sec-lbl">ריג'קטים השבוע (${allRejects.length})</div><table class="d"><thead><tr><th>מס'</th><th>ממצא</th><th>אחראי</th><th>יעד</th></tr></thead><tbody>${allRejects.map((r,i) => '<tr><td style="text-align:center;font-weight:700">' + (i+1) + '</td><td>' + (r.title||'—') + '</td><td>' + (r.assignee||'—') + '</td><td>' + fmtD(r.due) + '</td></tr>').join('')}</tbody></table></div>` : '';
          const win = window.open('', '_blank');
          win.document.write(`<!DOCTYPE html><html dir="rtl" lang="he"><head><meta charset="UTF-8"><title>דוח שבועי</title><link href="https://fonts.googleapis.com/css2?family=Assistant:wght@400;600;700&display=swap" rel="stylesheet"><style>*{margin:0;padding:0;box-sizing:border-box}body{font-family:'Assistant',Arial,sans-serif;direction:rtl;background:#fff;font-size:12px;-webkit-print-color-adjust:exact;print-color-adjust:exact}@page{size:A4 ${printOrientation};margin:0}thead{display:table-header-group}.hdr{position:fixed;top:0;left:0;right:0;width:100%;height:115px;z-index:100;background:#fff}.ftr{position:fixed;bottom:0;left:0;right:0;width:100%;height:64px;z-index:100;background:#fff}.lhh{background:#ebebeb;padding:14px 0 0;display:flex;justify-content:center}.lhh img{height:75px;object-fit:contain}.sg{height:3px;background:linear-gradient(to left,transparent 0%,#b5a882 30%,#b5a882 70%,transparent 100%);margin-top:-8px}.sn{height:2.5px;background:linear-gradient(to left,transparent 0%,#1a2c4a 30%,#1a2c4a 70%,transparent 100%)}.lhf{background:#c8bfa8;color:#4a3f2f;padding:9px 48px;text-align:center;font-size:10px;line-height:1.6}.fn{height:4px;background:linear-gradient(to left,transparent 0%,#1a2c4a 30%,#1a2c4a 70%,transparent 100%)}.fw{height:6px;background:#fff}.wm{position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);font-size:180px;font-weight:900;color:rgba(26,44,74,0.04);font-family:Georgia,serif;pointer-events:none;z-index:0;white-space:nowrap}.body{margin-top:115px;margin-bottom:68px;padding:12px 48px 20px}.badge{display:inline-block;padding:4px 12px;border-radius:2px;background:#1a2c4a;color:#fff;font-size:10px;font-weight:700;letter-spacing:1.2px}.mb{padding:12px 0;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #e8e8e8}.sec{margin-bottom:14px;break-inside:avoid;page-break-inside:avoid}.sec-lbl{font-size:10px;font-weight:700;color:#6b7280;letter-spacing:.5px;text-transform:uppercase;margin-bottom:6px}table.d{width:100%;border-collapse:collapse;font-size:11px}table.d th{background:#1a2c4a;color:#fff;padding:6px 10px;text-align:right;font-weight:600}table.d td{padding:6px 10px;border-bottom:1px solid #f0f0f0}</style></head><body><div class="wm">YBP</div><div class="hdr"><div class="lhh"><img src="${logoSrc}" alt="YBP"/></div><div class="sg"></div><div class="sn"></div></div><div class="ftr"><div class="fn"></div><div class="fw"></div><div class="lhf"><div>YBPROJECTS · ניהול פרויקטים בבנייה</div><div>זרחין 10, רעננה</div><div>yuval@ybprojects.com · office@ybprojects.com</div></div></div><div class="body"><div class="mb"><div><span class="badge">דוח שבועי</span></div><div style="text-align:left;font-size:11px;color:#6b7280">${fmtD(weekStart)} – ${fmtD(weekEnd)}<br/>${project?.name || ''}</div></div><div style="height:12px"></div>${contractorsHtml}${issuesHtml}${highlightsHtml}${summaryHtml}${nextWeekHtml}${rejectsHtml}</div></body></html>`);
          win.document.close();
          setTimeout(() => { win.focus(); win.print(); }, 1500);
        }} style={{
          padding: '7px 12px', borderRadius: 6, border: '1px solid #e5e7eb', background: '#fff',
          color: '#374151', fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
          display: 'flex', alignItems: 'center', gap: 6,
        }}>
          <Icon name="download" size={14}/> תצוגת PDF
        </button>
        <button
          onClick={handleSubmit}
          disabled={submitting}
          style={{
            padding: '8px 18px', borderRadius: 6, border: 'none',
            background: submitting ? '#9ca3af' : '#1a2c4a',
            color: '#fff', fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit',
          }}
        >{submitting ? 'מפיק דוח...' : 'הפק דוח'}</button>
      </header>

      <div style={{ maxWidth: 680, margin: '0 auto', padding: '24px 16px' }}>

        {/* Draft restore banner */}
        {showDraftBanner && (
          <div style={{ background:'#fffbeb', border:'1px solid #fbbf24', borderRadius:8, padding:'10px 14px', marginBottom:14, display:'flex', alignItems:'center', gap:10, fontSize:13, color:'#92400e' }}>
            <span style={{ fontSize:16 }}>📋</span>
            <span style={{ flex:1 }}>יש טיוטה שמורה לדוח זה{draftSavedAt ? ` — ${formatDraftAge(draftSavedAt)}` : ''}</span>
            <button onClick={() => setShowDraftBanner(false)} style={{ padding:'4px 12px', borderRadius:6, border:'none', background:'#f59e0b', color:'#fff', fontSize:12, fontWeight:700, cursor:'pointer', fontFamily:'inherit' }}>המשך עריכה</button>
            <button onClick={() => { if (window.cloudSave) window.cloudSave(draftKey, null).catch(()=>{}); else { try { localStorage.removeItem(draftKey); } catch(_){} } setShowDraftBanner(false); setSummary(''); setNextWeek(''); setHighlights(''); }} style={{ padding:'4px 10px', borderRadius:6, border:'1px solid #e5e7eb', background:'#fff', color:'#6b7280', fontSize:12, cursor:'pointer', fontFamily:'inherit' }}>התחל מחדש</button>
          </div>
        )}

        {/* Week range */}
        <div style={cardSt}>
          <div style={{ fontSize: 14, fontWeight: 700, color: '#1f2937', marginBottom: 14 }}>טווח שבועי</div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <div>
              <label style={labelSt}>מתאריך</label>
              <input type="date" value={weekStart} onChange={e => setWeekStart(e.target.value)} style={inputSt}/>
            </div>
            <div>
              <label style={labelSt}>עד תאריך</label>
              <input type="date" value={weekEnd} onChange={e => setWeekEnd(e.target.value)} style={inputSt}/>
            </div>
          </div>
        </div>

        {/* Generate All button */}
        <div style={{
          background: 'linear-gradient(135deg, #1a2c4a 0%, #2d4a7a 100%)',
          borderRadius: 10, padding: '16px 20px', marginBottom: 16,
          display: 'flex', alignItems: 'center', gap: 14,
        }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: '#fff', marginBottom: 3 }}>✦ הפק הכל עם AI</div>
            <div style={{ fontSize: 11, color: 'rgba(255,255,255,0.65)' }}>
              נקודות בולטות + סיכום שבוע + תחזית שבוע הבא — מהדוחות היומיים והגאנט
            </div>
          </div>
          <button
            onClick={generateAll}
            disabled={aiLoadingAll || (dailyReports.length === 0 && ganttItems.length === 0)}
            style={{
              padding: '10px 20px', borderRadius: 8, border: 'none',
              background: aiLoadingAll ? 'rgba(255,255,255,0.2)' : '#b5a882',
              color: '#1a2c4a', fontSize: 13, fontWeight: 800,
              cursor: aiLoadingAll ? 'wait' : 'pointer', fontFamily: 'inherit',
              whiteSpace: 'nowrap', transition: 'all 0.15s',
            }}
          >
            {aiLoadingAll ? '⟳ מייצר...' : '✦ הפק הכל'}
          </button>
        </div>

        {/* Previous weekly reports in same range */}
        {prevWeeklyReports.length > 0 && (
          <div style={{ ...cardSt, background: '#fffbeb', border: '1px solid #fde68a' }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: '#92400e', marginBottom: 10, display: 'flex', alignItems: 'center', gap: 8 }}>
              <span>📋</span>
              <span>דוחות שבועיים קודמים באותו טווח ({prevWeeklyReports.length})</span>
            </div>
            <div style={{ fontSize: 12, color: '#b45309', marginBottom: 12 }}>
              נמצאו דוחות שבועיים שנשלחו בטווח תאריכים חופף — למטה לייחוס בלבד
            </div>
            {prevWeeklyReports.map(r => <PrevWeeklyCard key={r.id} report={r}/>)}
          </div>
        )}

        {/* Auto-aggregated summary from daily reports */}
        <div style={{ ...cardSt, background: '#eff6ff', border: '1px solid #dbeafe' }}>
          <div style={{ fontSize: 14, fontWeight: 700, color: '#1d4ed8', marginBottom: 12 }}>
            📊 נמשך אוטומטית מ-{dailyReports.length} דוחות יומיים
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 12 }}>
            {[
              { label: 'ימי עבודה', value: totalWorkDays },
              { label: 'ימי עיכוב', value: delayDays },
              { label: "ריג'קטים חדשים", value: allRejects.length },
            ].map(({ label, value }) => (
              <div key={label} style={{
                background: '#fff', borderRadius: 8, padding: '12px 16px', textAlign: 'center',
                border: '1px solid #dbeafe',
              }}>
                <div style={{ fontSize: 26, fontWeight: 800, color: '#1a2c4a' }}>{value}</div>
                <div style={{ fontSize: 11, color: '#6b7280', marginTop: 2 }}>{label}</div>
              </div>
            ))}
          </div>

          {Object.keys(allContractors).length > 0 && (
            <div style={{ marginTop: 14 }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: '#374151', marginBottom: 8 }}>קבלנים פעילים השבוע</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                {Object.entries(allContractors).map(([trade, days]) => (
                  <div key={trade} style={{
                    padding: '4px 10px', borderRadius: 14, background: '#fff',
                    border: '1px solid #dbeafe', fontSize: 12, fontWeight: 600, color: '#1d4ed8',
                  }}>
                    {trade} <span style={{ opacity: 0.6, fontSize: 10 }}>({days} ימים)</span>
                  </div>
                ))}
              </div>
            </div>
          )}

          {allIssues.length > 0 && (
            <div style={{ marginTop: 14 }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: '#374151', marginBottom: 8 }}>בעיות שעלו השבוע</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {allIssues.map((iss, i) => (
                  <div key={i} style={{
                    padding: '8px 12px', background: '#fff', borderRadius: 6,
                    border: '1px solid #fde68a', borderRight: '3px solid #d97706',
                    fontSize: 12, color: '#713f12',
                  }}>
                    <span style={{ fontWeight: 700, color: '#6b7280' }}>{fmtD(iss.date)}: </span>
                    {iss.text}
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* Gantt forecast — next week */}
        <div style={cardSt}>
          <div style={{ fontSize: 14, fontWeight: 700, color: '#1f2937', marginBottom: 4, display: 'flex', alignItems: 'center', gap: 8 }}>
            <span>📅</span>
            <span>תחזית מהגאנט — שבוע הבא</span>
          </div>
          <div style={{ fontSize: 11, color: '#9ca3af', marginBottom: 14 }}>
            {fmtD(nextStart)} – {fmtD(nextEnd)} · משימות ושלבים פעילים
          </div>
          <GanttForecast
            items={ganttItems}
            nextStart={nextStart}
            nextEnd={nextEnd}
            onAutoFill={text => setNextWeek(prev => prev ? prev + '\n' + text : text)}
          />
        </div>

        {/* Highlights */}
        <div style={cardSt}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: '#1f2937' }}>נקודות בולטות השבוע</div>
            <button
              onClick={generateHighlights}
              disabled={aiLoadingHighlights || dailyReports.length === 0}
              title={dailyReports.length === 0 ? 'אין דוחות יומיים בטווח זה' : 'הפק אוטומטית מהדוחות היומיים'}
              style={{
                display: 'flex', alignItems: 'center', gap: 5,
                padding: '5px 12px', borderRadius: 6, border: 'none',
                background: aiLoadingHighlights ? '#e5e7eb' : (dailyReports.length === 0 ? '#f3f4f6' : '#7c3aed'),
                color: aiLoadingHighlights || dailyReports.length === 0 ? '#9ca3af' : '#fff',
                fontSize: 12, fontWeight: 700, cursor: dailyReports.length === 0 ? 'not-allowed' : 'pointer',
                fontFamily: 'inherit', transition: 'all 0.15s',
              }}
            >
              {aiLoadingHighlights
                ? <><span style={{ animation: 'spin 1s linear infinite', display: 'inline-block' }}>⟳</span> מכין...</>
                : <>✦ AI — הפק מהדוחות</>}
            </button>
          </div>
          <textarea
            value={highlights}
            onChange={e => setHighlights(e.target.value)}
            rows={3}
            placeholder={dailyReports.length > 0 ? 'לחץ ✦ AI לייצור אוטומטי מ-' + dailyReports.length + ' דוחות יומיים...' : 'ציוני דרך, פריצת דרך, אבני דרך שנפתרו...'}
            style={{ ...inputSt, resize: 'vertical', background: highlights ? '#fff' : '#fafafa' }}
          />
        </div>

        {/* Summary */}
        <div style={cardSt}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
            <div style={{ fontSize: 14, fontWeight: 700, color: '#1f2937' }}>סיכום שבוע</div>
            <button
              onClick={generateSummary}
              disabled={aiLoadingSummary || dailyReports.length === 0}
              title={dailyReports.length === 0 ? 'אין דוחות יומיים בטווח זה' : 'הפק אוטומטית מהדוחות היומיים'}
              style={{
                display: 'flex', alignItems: 'center', gap: 5,
                padding: '5px 12px', borderRadius: 6, border: 'none',
                background: aiLoadingSummary ? '#e5e7eb' : (dailyReports.length === 0 ? '#f3f4f6' : '#7c3aed'),
                color: aiLoadingSummary || dailyReports.length === 0 ? '#9ca3af' : '#fff',
                fontSize: 12, fontWeight: 700, cursor: dailyReports.length === 0 ? 'not-allowed' : 'pointer',
                fontFamily: 'inherit', transition: 'all 0.15s',
              }}
            >
              {aiLoadingSummary
                ? <><span style={{ animation: 'spin 1s linear infinite', display: 'inline-block' }}>⟳</span> מכין...</>
                : <>✦ AI — הפק מהדוחות</>}
            </button>
          </div>
          <textarea
            value={summary}
            onChange={e => setSummary(e.target.value)}
            rows={4}
            placeholder={dailyReports.length > 0 ? 'לחץ ✦ AI לייצור אוטומטי מ-' + dailyReports.length + ' דוחות יומיים...' : 'סיכום כללי של ביצועי השבוע, ההתקדמות, מצב הפרויקט...'}
            style={{ ...inputSt, resize: 'vertical', background: summary ? '#fff' : '#fafafa' }}
          />
        </div>

        {/* Next week plan */}
        <div style={cardSt}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ fontSize: 14, fontWeight: 700, color: '#1f2937' }}>תחזית שבוע הבא</span>
              {nextWeek && (
                <span style={{
                  fontSize: 10, padding: '2px 8px', borderRadius: 10,
                  background: '#dcfce7', color: '#166534', fontWeight: 700,
                }}>מולא</span>
              )}
            </div>
            <button
              onClick={generateNextWeek}
              disabled={aiLoadingNextWeek}
              style={{
                display: 'flex', alignItems: 'center', gap: 5,
                padding: '5px 12px', borderRadius: 6, border: 'none',
                background: aiLoadingNextWeek ? '#e5e7eb' : '#7c3aed',
                color: aiLoadingNextWeek ? '#9ca3af' : '#fff',
                fontSize: 12, fontWeight: 700, cursor: aiLoadingNextWeek ? 'wait' : 'pointer',
                fontFamily: 'inherit',
              }}
            >
              {aiLoadingNextWeek ? '⟳ מכין...' : '✦ AI — גאנט + דוחות'}
            </button>
          </div>
          <div style={{ fontSize: 11, color: '#9ca3af', marginBottom: 10 }}>
            {fmtD(nextStart)} – {fmtD(nextEnd)} · AI ממזג נתוני גאנט + המשך מהשבוע
          </div>
          <textarea
            value={nextWeek}
            onChange={e => setNextWeek(e.target.value)}
            rows={5}
            placeholder="לחץ ✦ AI לתחזית אוטומטית מהגאנט, או כתוב ידנית..."
            style={{ ...inputSt, resize: 'vertical', background: nextWeek ? '#fff' : '#fafafa' }}
          />
        </div>

        {/* Open tasks for this project */}
        {(() => {
          const openTasks = (store.tasks || []).filter(t =>
            t.projectId === projectId && !['done', 'archived', 'הסתיים', 'אושר'].includes(t.status)
          );
          if (openTasks.length === 0) return null;
          const sevColor = { critical:'#dc2626', high:'#c2410c', medium:'#d97706', low:'#16a34a' };
          return (
            <div style={cardSt}>
              <div style={{ fontSize: 14, fontWeight: 700, color: '#1f2937', marginBottom: 12, display:'flex', alignItems:'center', gap:8 }}>
                <span>✅</span>
                <span>משימות פתוחות ({openTasks.length})</span>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {openTasks.map(t => (
                  <div key={t.id} style={{
                    display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px',
                    background: '#f9fafb', borderRadius: 6, border: '1px solid #e5e7eb',
                  }}>
                    <span style={{
                      width: 8, height: 8, borderRadius: '50%', flexShrink: 0,
                      background: sevColor[t.severity] || '#9ca3af',
                    }}/>
                    <span style={{ flex: 1, fontSize: 13, color: '#1f2937' }}>{t.title}</span>
                    {t.assignee && <span style={{ fontSize: 11, color: '#6b7280', flexShrink: 0 }}>{t.assignee}</span>}
                    {t.due && <span style={{ fontSize: 11, color: '#9ca3af', flexShrink: 0 }}>{fmtD(t.due)}</span>}
                  </div>
                ))}
              </div>
            </div>
          );
        })()}

        <button onClick={handleDeleteDraft} style={{
          width:'100%', padding:'10px', borderRadius:8,
          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', justifyContent:'center', gap:6,
          marginBottom:10,
        }}>🗑 מחק טיוטה</button>

        <button
          onClick={handleSubmit}
          disabled={submitting}
          style={{
            width: '100%', padding: '14px', borderRadius: 8, border: 'none',
            background: submitting ? '#9ca3af' : '#1a2c4a',
            color: '#fff', fontSize: 15, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit',
            marginBottom: 32,
          }}
        >{submitting ? 'מפיק דוח...' : 'הפק דוח'}</button>

      </div>

      {/* פאנל הצלחה — מופיע אחרי הפקת דוח */}
      {submittedReport && (
        <div style={{
          position: 'fixed', bottom: 0, 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>
  );
};

window.WeeklyReportForm = WeeklyReportForm;

// Global helper: build PDF HTML parts for a submitted weekly report
// Used by report-viewer.jsx ensureDriveUrl when report.kind === 'weekly'
window.YBP_WEEKLY_BUILD_HTML = function(report, projectObj) {
  const c = report.content || {};
  const fmtD = function(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 contractors = c.contractors || [];
  const issues = c.issues || [];
  const highlights = c.highlights || '';
  const summary = c.summary || '';
  const nextWeek = c.nextWeek || '';
  const rejects = report.rejects || [];
  const weekStart = c.weekStart || report.date || '';
  const weekEnd   = c.weekEnd   || report.date || '';

  const contractorsHtml = contractors.length
    ? '<div class="sec"><div class="sec-lbl">קבלנים פעילים השבוע</div><div style="display:flex;flex-wrap:wrap;gap:5px">' +
      contractors.map(function(co) {
        return '<span style="padding:4px 10px;border-radius:12px;background:#eff6ff;color:#1d4ed8;font-size:11px;font-weight:600;border:1px solid #dbeafe">' +
          co.trade + (co.days ? ' <span style="opacity:0.6">(' + co.days + ' ימים)</span>' : '') + '</span>';
      }).join('') + '</div></div>' : '';

  const issuesHtml = (Array.isArray(issues) && issues.length)
    ? '<div class="sec"><div class="sec-lbl">בעיות שעלו השבוע</div>' +
      issues.map(function(iss) {
        return '<div style="padding:8px 10px;background:#fef3c7;border-right:3px solid #d97706;border-radius:4px;font-size:11px;color:#713f12;margin-bottom:4px"><strong>' +
          fmtD(iss.date) + ':</strong> ' + (iss.text || '') + '</div>';
      }).join('') + '</div>'
    : (typeof issues === 'string' && issues
        ? '<div class="sec"><div class="sec-lbl">בעיות</div><div style="padding:8px 10px;background:#fef3c7;border-right:3px solid #d97706;border-radius:4px;font-size:11px;color:#713f12">' + issues + '</div></div>'
        : '');

  const highlightsHtml = highlights
    ? '<div class="sec"><div class="sec-lbl">נקודות בולטות</div><div style="font-size:11.5px;color:#374151;line-height:1.6;white-space:pre-wrap">' + highlights + '</div></div>' : '';
  const summaryHtml = summary
    ? '<div class="sec"><div class="sec-lbl">סיכום שבוע</div><div style="font-size:11.5px;color:#374151;line-height:1.6;white-space:pre-wrap">' + summary + '</div></div>' : '';
  const nextWeekHtml = nextWeek
    ? '<div class="sec"><div class="sec-lbl">תחזית שבוע הבא</div><div style="font-size:11.5px;color:#374151;line-height:1.6;white-space:pre-wrap">' + nextWeek + '</div></div>' : '';
  const rejectsHtml = rejects.length
    ? '<div class="sec"><div class="sec-lbl">ריג\'קטים השבוע (' + rejects.length + ')</div>' +
      '<table class="d"><thead><tr><th>מס\'</th><th>ממצא</th><th>אחראי</th><th>יעד</th></tr></thead><tbody>' +
      rejects.map(function(r, i) {
        return '<tr><td style="text-align:center;font-weight:700">' + (i+1) + '</td><td>' + (r.title||'—') + '</td><td>' + (r.assignee||'—') + '</td><td>' + fmtD(r.due) + '</td></tr>';
      }).join('') + '</tbody></table></div>' : '';

  const projName = (projectObj && projectObj.name) || '';
  const projAddr = (projectObj && projectObj.address) ? ' · ' + projectObj.address : '';
  const headerMetaHtml =
    '<div class="mb"><div><span class="badge">דוח שבועי</span></div>' +
    '<div style="text-align:left;font-size:11px;color:#6b7280">' + fmtD(weekStart) + ' – ' + fmtD(weekEnd) + '<br/>' + projName + '</div></div>' +
    '<div class="sec" style="padding-bottom:8px">' +
    '<h2 style="font-size:22px;font-weight:700;color:#0f1e38;line-height:1.2;margin-bottom:6px">דוח שבועי — ' + fmtD(weekStart) + ' עד ' + fmtD(weekEnd) + '</h2>' +
    (projName ? '<div style="font-size:13px;color:#6b7280">פרויקט: <strong style="color:#1f2937">' + projName + '</strong>' + projAddr + '</div>' : '') +
    '</div>';

  const bodyHtml = [contractorsHtml, issuesHtml, highlightsHtml, summaryHtml, nextWeekHtml, rejectsHtml].join('');
  return { headerMetaHtml, bodyHtml };
};

})();
