// Report Viewer — תצוגת דוח שנשלח (יומי/שבועי/ריג'קטים)
(function(){
const { useState, useEffect, useMemo } = React;

// Build plain-text summary of report for sharing
const buildReportText = (report, project, driveUrl) => {
  const c = report?.content || {};
  const kindMap = { daily:'דוח יומי', weekly:'דוח שבועי', rejects:'דוח ריג׳קטים', infra:'דוח תשתיות' };
  const lines = [
    `📋 ${kindMap[report?.kind] || 'דוח'} | ${report?.id}`,
    `📁 פרויקט: ${project?.name || report?.project || ''}`,
    `📅 תאריך: ${fmtDateHe(report?.date)}`,
    `👤 ${report?.author}`,
    ``,
    report?.title ? `*${report.title}*` : '',
    c.notes ? `📝 הערות: ${c.notes}` : '',
    c.issues ? `⚠️ בעיות: ${c.issues}` : '',
    c.contractors?.length ? `👷 קבלנים: ${c.contractors.map(x=>x.trade).join(', ')}` : '',
    report?.rejects?.length ? `🔴 ריג׳קטים: ${report.rejects.length} פריטים` : '',
    ``,
    `YBPROJECTS · ניהול פרוייקטים בבנייה`,
    driveUrl ? `\n📎 צפייה ב-PDF המלא:\n${driveUrl}` : '',
  ].filter(Boolean).join('\n');
  return lines;
};

const ReportViewer = ({ reportId, onBack, onEdit }) => {
  const { isMobile } = useViewport();
  const [store, setStore] = useState(SyncStore.get());
  const [showSendMenu, setShowSendMenu] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [printOrientation, setPrintOrientation] = useState('portrait');
  const [showSigPad, setShowSigPad] = useState(false);
  const [sigDataUrl, setSigDataUrl] = useState(() => {
    try {
      const stored = localStorage.getItem('ybp_sig_' + reportId);
      if (stored) return stored;
      const u = window.YBP_AUTH && window.YBP_AUTH.getCurrentUser && window.YBP_AUTH.getCurrentUser();
      return (u && u.signatureImage) || null;
    } catch { return null; }
  });
  const canvasRef = React.useRef(null);
  const drawing = React.useRef(false);

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

  const PDF_WH_FALLBACK = 'https://hook.eu2.make.com/cwhco2m6u2m48ey692n7n7wagoz8cg0i';
  const getPdfWebhookUrl = () => getWebhookUrl('PLACEHOLDER_UPLOAD_REPORT_PDF') || PDF_WH_FALLBACK;

  const buildReportHtml = (rep, proj) => {
    if (!window.YBPPdf || !window.YBPPdf.buildLetterheadHtml) return '';
    const logoSrc = document.querySelector('img[alt="YBP"]')?.src || '';
    let headerMetaHtml = '', bodyHtml = '';
    if (rep.kind === 'weekly' && window.YBP_WEEKLY_BUILD_HTML) {
      const parts = window.YBP_WEEKLY_BUILD_HTML(rep, proj);
      headerMetaHtml = parts.headerMetaHtml;
      bodyHtml = parts.bodyHtml;
    }
    return window.YBPPdf.buildLetterheadHtml({ orientation: 'portrait', logoSrc, fileName: rep.title || 'report', headerMetaHtml, bodyHtml, sigHtml: '' });
  };

  const saveReportToDrive = async (report) => {
    const webhookUrl = getPdfWebhookUrl();
    const pmName = (window.YBP_AUTH && window.YBP_AUTH.getCurrentUser && window.YBP_AUTH.getCurrentUser().name) || 'מנהל';
    const projectObj = YBP_DATA.projects.find(p => p.id === report?.projectId) || {};
    const kindMap = { daily: 'דוח יומי', weekly: 'דוח שבועי', rejects: 'דוח ריג׳קטים', infra: 'דוח תשתיות' };
    if (window.toastInfo) window.toastInfo('שומר ל-Drive...');
    try {
      const html = buildReportHtml(report, projectObj);
      const resp = await fetch(webhookUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          _sk: '1h4M4SEXbhoYF1YVW1mS6YJZs84yxSVHaBjPDDxMpbak',
          manager: pmName,
          project: projectObj.name || report?.projectId || '',
          project_id: report?.projectId || '',
          type_name: kindMap[report?.kind] || 'דוח',
          date: report?.date || new Date().toISOString().slice(0, 10),
          report_id: report?.id || '',
          rejects_count: report?.rejects?.length || 0,
          format: 'html',
          html,
        }),
      });
      const data = await resp.json().catch(() => ({}));
      const url = data.url || data.file_url || data.driveUrl || null;
      if (url) {
        SyncStore.updateReport(report.id, { driveUrl: url });
        if (window.toastSuccess) window.toastSuccess('הדוח נשמר ב-Drive ✓');
      } else {
        if (window.toastError) window.toastError('שגיאה בשמירה ל-Drive');
      }
    } catch {
      if (window.toastError) window.toastError('שגיאת חיבור ל-Drive');
    }
  };

  // Upload report HTML to Drive and return the URL — uses cached driveUrl if already uploaded
  const ensureDriveUrl = async (report) => {
    if (report.driveUrl) return report.driveUrl;
    const webhookUrl = getPdfWebhookUrl();
    const pmName = (window.YBP_AUTH && window.YBP_AUTH.getCurrentUser && window.YBP_AUTH.getCurrentUser().name) || 'מנהל';
    const projectObj = YBP_DATA.projects.find(p => p.id === report.projectId) || {};
    if (window.toastInfo) window.toastInfo('מעלה דוח ל-Drive...');
    try {
      const html = buildReportHtml(report, projectObj);
      if (!html) { if (window.toastError) window.toastError('שגיאה ביצירת HTML לדוח'); return null; }
      const resp = await fetch(webhookUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          _sk: '1h4M4SEXbhoYF1YVW1mS6YJZs84yxSVHaBjPDDxMpbak',
          projectId: report.projectId,
          reportId: report.id,
          format: 'html',
          html,
          manager: pmName,
          project: projectObj.name || '',
          type_name: ({ daily:'דוח יומי', weekly:'דוח שבועי', rejects:'דוח ריג׳קטים', infra:'דוח תשתיות' })[report.kind] || 'דוח',
          date: report.date,
        }),
      });
      if (!resp.ok) { if (window.toastError) window.toastError('שגיאה בהעלאת הדוח'); return null; }
      const data = await resp.json().catch(() => ({}));
      const url = data.url || data.file_url || data.driveUrl || null;
      if (url) {
        SyncStore.updateReport(report.id, { driveUrl: url });
        if (window.toastSuccess) window.toastSuccess('דוח הועלה ✓');
      }
      return url;
    } catch { if (window.toastError) window.toastError('שגיאת חיבור'); return null; }
  };

  useEffect(() => SyncStore.subscribe(setStore), []);
  useEffect(() => {
    if (!showSendMenu) return;
    const close = () => setShowSendMenu(false);
    setTimeout(() => document.addEventListener('click', close), 0);
    return () => document.removeEventListener('click', close);
  }, [showSendMenu]);
  const report = (store.reports || []).find(r => r.id === reportId);
  const project = report ? YBP_DATA.projects.find(p => p.id === report.projectId) : null;

  if (!report) {
    return (
      <div style={{ padding:40, textAlign:'center', color:'#9ca3af' }}>
        דוח לא נמצא.
        <br/>
        <button onClick={onBack} style={{ marginTop:16, padding:'8px 18px', background:'#1d4ed8', color:'#fff', border:'none', borderRadius:6, cursor:'pointer' }}>חזרה</button>
      </div>
    );
  }

  const c = report.content || {};
  const statusOpt = YBP_DAY_STATUS?.find(s => s.k === c.dayStatus);

  const KindBadge = () => {
    const map = {
      daily: { label:'דוח יומי', color:'#1d4ed8', bg:'#eff6ff' },
      weekly: { label:'דוח שבועי', color:'#7c3aed', bg:'#f3e8ff' },
      rejects: { label:'דוח ריג׳קטים', color:'#dc2626', bg:'#fee2e2' },
      infra: { label:'תיעוד תשתיות', color:'#9333ea', bg:'#fdf4ff' },
    };
    const m = map[report.kind] || { label: report.kind, color:'#6b7280', bg:'#f3f4f6' };
    return (
      <span style={{
        padding:'3px 10px', borderRadius:12, fontSize:11, fontWeight:700,
        background:m.bg, color:m.color,
      }}>{m.label}</span>
    );
  };

  return (
    <div style={{ minHeight:'100%', background:'#e8eaed', fontFamily:'Assistant, sans-serif', direction:'rtl' }}>

      {/* ── Signature Pad Modal ─────────────────────────────────────────── */}
      {showSigPad && (
        <div style={{
          position:'fixed', inset:0, background:'rgba(0,0,0,0.5)', zIndex:1000,
          display:'flex', alignItems:'center', justifyContent:'center',
        }} onClick={() => setShowSigPad(false)}>
          <div style={{
            background:'#fff', borderRadius:12, padding:24, width:380, maxWidth:'95vw',
            boxShadow:'0 20px 60px rgba(0,0,0,0.3)',
          }} onClick={e => e.stopPropagation()}>
            <div style={{ fontSize:15, fontWeight:700, color:'#1f2937', marginBottom:4 }}>חתימה דיגיטלית</div>
            <div style={{ fontSize:12, color:'#9ca3af', marginBottom:14 }}>חתום בתוך המסגרת עם האצבע או העכבר</div>
            <canvas
              ref={canvasRef}
              width={332} height={140}
              style={{ border:'1px solid #e5e7eb', borderRadius:8, display:'block', cursor:'crosshair', background:'#fafafa', touchAction:'none' }}
              onMouseDown={e => {
                drawing.current = true;
                const r = canvasRef.current.getBoundingClientRect();
                const ctx = canvasRef.current.getContext('2d');
                ctx.beginPath(); ctx.moveTo(e.clientX-r.left, e.clientY-r.top);
              }}
              onMouseMove={e => {
                if (!drawing.current) return;
                const r = canvasRef.current.getBoundingClientRect();
                const ctx = canvasRef.current.getContext('2d');
                ctx.lineTo(e.clientX-r.left, e.clientY-r.top);
                ctx.strokeStyle='#1a2c4a'; ctx.lineWidth=2.5; ctx.lineCap='round'; ctx.stroke();
              }}
              onMouseUp={() => { drawing.current = false; }}
              onMouseLeave={() => { drawing.current = false; }}
              onTouchStart={e => {
                e.preventDefault();
                drawing.current = true;
                const r = canvasRef.current.getBoundingClientRect();
                const t = e.touches[0];
                const ctx = canvasRef.current.getContext('2d');
                ctx.beginPath(); ctx.moveTo(t.clientX-r.left, t.clientY-r.top);
              }}
              onTouchMove={e => {
                e.preventDefault();
                if (!drawing.current) return;
                const r = canvasRef.current.getBoundingClientRect();
                const t = e.touches[0];
                const ctx = canvasRef.current.getContext('2d');
                ctx.lineTo(t.clientX-r.left, t.clientY-r.top);
                ctx.strokeStyle='#1a2c4a'; ctx.lineWidth=2.5; ctx.lineCap='round'; ctx.stroke();
              }}
              onTouchEnd={() => { drawing.current = false; }}
            />
            <div style={{ display:'flex', gap:8, marginTop:14, justifyContent:'space-between' }}>
              <button onClick={() => {
                const ctx = canvasRef.current.getContext('2d');
                ctx.clearRect(0,0,332,140);
              }} style={{
                padding:'8px 14px', borderRadius:6, border:'1px solid #e5e7eb',
                background:'#fff', color:'#6b7280', fontSize:12, fontWeight:600,
                cursor:'pointer', fontFamily:'inherit',
              }}>נקה</button>
              <div style={{ display:'flex', gap:8 }}>
                <button onClick={() => setShowSigPad(false)} style={{
                  padding:'8px 14px', borderRadius:6, border:'1px solid #e5e7eb',
                  background:'#fff', color:'#374151', fontSize:12, fontWeight:600,
                  cursor:'pointer', fontFamily:'inherit',
                }}>ביטול</button>
                <button onClick={() => {
                  const url = canvasRef.current.toDataURL('image/png');
                  setSigDataUrl(url);
                  try { localStorage.setItem('ybp_sig_' + reportId, url); } catch {}
                  setShowSigPad(false);
                }} style={{
                  padding:'8px 18px', borderRadius:6, border:'none',
                  background:'#1a2c4a', color:'#fff', fontSize:12, fontWeight:700,
                  cursor:'pointer', fontFamily:'inherit',
                }}>שמור חתימה</button>
              </div>
            </div>
          </div>
        </div>
      )}
      <header style={{
        background:'#fff', borderBottom:'1px solid #e5e7eb', padding: isMobile ? '10px 12px' : '12px 24px',
        display:'flex', alignItems:'center', gap: isMobile ? 6 : 12, flexWrap:'wrap',
        position:'sticky', top:0, zIndex:10,
      }} className="no-print">
        <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' }}/>
        <KindBadge/>
        <div style={{ flex:1, display:'flex', alignItems:'center', gap:8 }}>
          <span style={{ fontSize:12, color:'#6b7280', fontFamily:'ui-monospace, Menlo, monospace', fontWeight:600 }}>{report.id}</span>
          {report.project && <span style={{ fontSize:13, color:'#1f2937', fontWeight:600 }}>· {report.project}</span>}
        </div>
        {/* כיוון הדפסה */}
        <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 style={actionBtnSt} onClick={() => {
    const fmtD = (iso) => { if (!iso) return '—'; const d = new Date(iso); return String(d.getDate()).padStart(2,'0')+'/'+String(d.getMonth()+1).padStart(2,'0')+'/'+d.getFullYear(); };
    const kindHe = { daily:'יומי', weekly:'שבועי', rejects:'ריגקטים', meeting:'פגישה', infra:'תשתיות' }[report?.kind] || 'דוח';
    const kindLabel = { daily:'DAILY REPORT', weekly:'WEEKLY REPORT', rejects:'REJECTS REPORT', meeting:'MEETING REPORT', infra:'INFRA REPORT' }[report?.kind] || 'REPORT';
    const logoSrc = document.querySelector('img[alt="YBP"]')?.src || '';
    const dt = new Date(report?.date || Date.now());
    const dateStr = fmtD(report?.date);
    const fileName = String(dt.getDate()).padStart(2,'0')+'-'+String(dt.getMonth()+1).padStart(2,'0')+'-'+dt.getFullYear()+'_'+(project?.name||'')+'_'+kindHe;
    const cr = report?.content || {};
    const rejectsHtml = report?.rejects?.length ? `<div class="sec"><div class="sec-lbl">ריג'קטים (${report.rejects.length})</div><table class="d"><thead><tr><th style="width:26px">מס'</th><th>ממצא ריג'קט</th><th>תיאור</th><th>אחראי</th><th>תאריך יעד</th><th>תאריך ממצא 🔒</th><th>תמונות</th></tr></thead><tbody>${report.rejects.map((r,i)=>{const photos=r.photos||(r.photo?[r.photo]:[]);return '<tr class="reject-card"><td style="text-align:center;font-weight:700;color:#1a2c4a">'+(i+1)+'</td><td style="font-weight:600;color:#1f2937">'+(r.title||'—')+'</td><td style="font-size:10px;color:#4b5563">'+(r.description||'—')+'</td><td style="font-size:10px">'+(r.assignee||'—')+'</td><td style="font-weight:600;color:#1a2c4a;font-size:10px">'+fmtD(r.due)+'</td><td style="color:#9ca3af;font-size:10px">'+fmtD(r.createdAt||report?.date)+'</td><td>'+(photos.length===0?'—':'<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(80px,1fr));gap:3px">'+photos.map(ph=>'<img src="'+ph+'" style="width:100%;height:auto;max-height:90px;object-fit:contain;background:#f9fafb;border-radius:2px;border:1px solid #e5e7eb;display:block"/>').join('')+'</div>')+'</td></tr>';}).join('')}</tbody></table></div>` : '';
    const contractorsHtml = cr.contractors?.length ? `<div class="sec"><div class="sec-lbl">קבלנים באתר</div><div style="display:flex;flex-wrap:wrap;gap:5px">${cr.contractors.map(co=>'<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.count?' × '+co.count:'')+'</span>').join('')}</div></div>` : '';
    const issuesHtml = cr.issues ? `<div class="sec"><div class="sec-lbl">בעיות</div><div style="padding:10px;background:#fef3c7;border-radius:5px;font-size:11px;color:#713f12;border-right:3px solid #d97706">${cr.issues}</div></div>` : '';
    const notesHtml = cr.notes ? `<div class="sec"><div class="sec-lbl">הערות</div><div style="font-size:11.5px;color:#374151;line-height:1.6">${cr.notes}</div></div>` : '';
    const dayStatusHtml = cr.dayStatus ? `<div class="sec"><div class="sec-lbl">סטטוס יום</div><div style="padding:7px 10px;background:#d1fae5;border-right:3px solid #10b981;border-radius:4px;font-size:12px;font-weight:700;color:#065f46">${cr.dayStatus==='normal'?'✓ יום עבודה תקין':cr.dayStatus==='delayed'?'⚠️ עיכובים':''+cr.dayStatus}${cr.statusReason?' — '+cr.statusReason:''}</div></div>` : '';
    const progressHtml = cr.progress?.length ? `<div class="sec"><div class="sec-lbl">התקדמות</div>${cr.progress.map(p=>'<div style="display:flex;align-items:center;gap:7px;padding:5px 8px;background:#f0fdf4;border-radius:4px;margin-bottom:3px"><span style="color:#10b981">✓</span><span style="flex:1;font-size:11px">'+(p.title||'')+'</span><span style="font-size:11px;font-weight:700;color:#1d4ed8">'+(p.percentDone||0)+'%</span></div>').join('')}</div>` : '';
    const suppliersHtml = cr.suppliers?.filter(s=>s.name||s.item).length ? `<div class="sec"><div class="sec-lbl">ספקים / חומרים שהגיעו</div><table class="d"><thead><tr><th>ספק</th><th>פריט</th><th>הערה</th></tr></thead><tbody>${cr.suppliers.filter(s=>s.name||s.item).map(s=>'<tr><td>'+(s.name||'')+'</td><td>'+(s.item||'')+'</td><td style="color:#6b7280">'+(s.note||'—')+'</td></tr>').join('')}</tbody></table></div>` : '';
    const visitsHtml = cr.visits?.filter(v=>v.name).length ? `<div class="sec"><div class="sec-lbl">ביקורים באתר</div>${cr.visits.filter(v=>v.name).map(v=>'<div style="padding:5px 8px;background:#fafbfc;border-radius:4px;font-size:11px;margin-bottom:3px"><strong>'+(v.name||'')+'</strong>'+(v.role?' · '+v.role:'')+'</div>').join('')}</div>` : '';
    
    const CSS = `*{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 portrait;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}.mb{padding:12px 0;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #e8e8e8}.badge{display:inline-block;padding:4px 12px;border-radius:2px;background:#1a2c4a;color:#fff;font-size:10px;font-weight:700;letter-spacing:1.2px}.content{padding:14px 0 20px;display:flex;flex-direction:column;gap:12px;flex:1}.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:8px;text-align:right;font-weight:700;font-size:10px;border:1px solid #14213a;white-space:nowrap}table.d tr:nth-child(odd)>td{background:#fff}table.d tr:nth-child(even)>td{background:#f8f9fa}table.d td{padding:8px;border:1px solid #e5e7eb;vertical-align:top}.sig{padding:18px 0 24px;border-top:1px solid #e5e7eb;display:grid;grid-template-columns:1fr 1fr;gap:32px;page-break-inside:avoid;break-inside:avoid;margin-top:auto}`;

    // ── Weekly-specific PDF content ──────────────────────────────────────────
    const isWeekly = report?.kind === 'weekly';
    const weeklyKpiHtml = isWeekly ? '<div class="sec"><div style="display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-bottom:10px">'
      + [['ימי עבודה', cr.totalWorkDays||0],['ימי עיכוב', cr.delayDays||0],["ריג'קטים", report.rejects?.length||0]]
        .map(([l,v])=>'<div style="background:#f9fafb;border:1px solid #e5e7eb;border-radius:6px;padding:10px;text-align:center"><div style="font-size:22px;font-weight:800;color:#1a2c4a">'+v+'</div><div style="font-size:10px;color:#6b7280;margin-top:2px">'+l+'</div></div>').join('')
      + '</div></div>' : '';
    const weeklyContractorsHtml = isWeekly && cr.contractors?.length ? '<div class="sec"><div class="sec-lbl">קבלנים פעילים</div><div style="display:flex;flex-wrap:wrap;gap:5px">'
      + cr.contractors.map(co=>'<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?' ('+co.days+' ימים)':'')+'</span>').join('')
      + '</div></div>' : '';
    const weeklyIssuesHtml = isWeekly && cr.issues?.length ? '<div class="sec"><div class="sec-lbl">בעיות שעלו השבוע</div>'
      + cr.issues.map(iss=>'<div style="padding:7px 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 = isWeekly && cr.highlights ? '<div class="sec"><div class="sec-lbl">נקודות בולטות</div><div style="padding:10px 12px;background:#f0fdf4;border-right:3px solid #22c55e;border-radius:4px;font-size:11.5px;color:#14532d;line-height:1.7;white-space:pre-wrap">'+cr.highlights+'</div></div>' : '';
    const summaryHtml = isWeekly && cr.summary ? '<div class="sec"><div class="sec-lbl">סיכום שבוע</div><div style="padding:10px 12px;background:#f9fafb;border:1px solid #e5e7eb;border-radius:4px;font-size:11.5px;color:#374151;line-height:1.7;white-space:pre-wrap">'+cr.summary+'</div></div>' : '';
    const nextWeekHtml = isWeekly && cr.nextWeek ? '<div class="sec"><div class="sec-lbl">תחזית שבוע הבא</div><div style="padding:10px 12px;background:#eff6ff;border-right:3px solid #3b82f6;border-radius:4px;font-size:11.5px;color:#1e3a5f;line-height:1.7;white-space:pre-wrap">'+cr.nextWeek+'</div></div>' : '';

    // ── Infra items ──
    const infraItemsHtml = (report?.kind === 'infra' && cr.items?.length) ? (() => {
      const ST = { ok:{color:'#10b981',bg:'#d1fae5',label:'תקין'}, issue:{color:'#f59e0b',bg:'#fef3c7',label:'טעון טיפול'}, critical:{color:'#dc2626',bg:'#fee2e2',label:'בעיה קריטית'} };
      const ICONS = { foundation:'🏗️',envelope:'🧱',plumbing:'🔧',electric:'⚡',lowvoltage:'📡',gas:'🔥',hvac:'❄️',fire:'🚿',plaster:'🪣',flooring:'⬜',facade:'🏢',drainage:'🌊',insulation:'🛡️',other:'📋' };
      const LBLS  = { foundation:'יסודות ושלד',envelope:'מעטפת',plumbing:'אינסטלציה',electric:'חשמל',lowvoltage:'מתח נמוך',gas:'גז',hvac:'מיזוג אוויר',fire:'אש וגילוי עשן',plaster:'טיח וגבס',flooring:'ריצוף ואריחים',facade:'חזיתות',drainage:'ניקוז וביוב',insulation:'איטום',other:'אחר' };
      return '<div class="sec"><div class="sec-lbl">סעיפי תשתית ('+cr.items.length+')</div>'
        + cr.items.map((item,i)=>{
            const st=ST[item.status]||ST.ok; const photos=item.photos||[];
            return '<div class="infra-item" style="border:1px solid '+st.color+';border-right:4px solid '+st.color+'">'
              +'<div style="display:flex;align-items:center;gap:8px;padding:9px 12px;background:'+st.bg+'">'
              +'<span style="font-size:11px;font-weight:800;width:20px;text-align:center">'+(i+1)+'</span>'
              +'<span style="font-size:15px">'+(ICONS[item.infraType]||'📋')+'</span>'
              +'<span style="flex:1;font-size:13px;font-weight:700;color:#1f2937">'+(LBLS[item.infraType]||item.infraType)+'</span>'
              +(item.location?'<span style="font-size:11px;color:#6b7280">📍 '+item.location+'</span>':'')
              +'<span style="font-size:10px;font-weight:700;padding:2px 8px;border-radius:10px;background:rgba(255,255,255,0.7);color:'+st.color+'">'+st.label+'</span>'
              +'</div>'
              +(item.description?'<div style="padding:10px 12px;font-size:12px;color:#374151;line-height:1.5">'+item.description+'</div>':'')
              +(photos.length?'<div style="padding:10px 12px;display:flex;flex-wrap:wrap;gap:6px">'+photos.map(ph=>'<img src="'+ph+'" style="width:90px;height:90px;object-fit:cover;border-radius:6px;border:1px solid #e5e7eb">').join('')+'</div>':'')
              +'</div>';
          }).join('')+'</div>';
    })() : '';

    // ── Header meta (badge + title + meta grid) ──
    const headerMetaHtml = `
      <div class="mb">
        <div><span class="badge">${kindLabel}</span></div>
        <div style="text-align:left">
          <div style="font-family:ui-monospace,Menlo,monospace;font-size:13px;font-weight:700;color:#1a2c4a">${report?.id}</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:#0f1e38;line-height:1.2;margin-bottom:6px">${report?.title||''}</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:#f9fafb;border-radius:4px;border:1px solid #e5e7eb">
        <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">${report?.author||''}</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">נשלח</div></div>
      </div>
    `;

    // ── Body sections ──
    const bodyHtml = [
      isWeekly ? weeklyKpiHtml : '',
      isWeekly ? weeklyContractorsHtml : '',
      isWeekly ? weeklyIssuesHtml : '',
      isWeekly ? highlightsHtml : '',
      isWeekly ? summaryHtml : '',
      isWeekly ? nextWeekHtml : '',
      dayStatusHtml,
      contractorsHtml,
      progressHtml,
      rejectsHtml,
      issuesHtml,
      suppliersHtml,
      visitsHtml,
      notesHtml,
      infraItemsHtml,
    ].join('');

    // ── Signature ──
    const sigHtml = `
      <div class="sig">
        <div>
          <div style="height:48px;border-bottom:1px solid #1a2c4a;margin-bottom:8px;display:flex;align-items:flex-end;padding-bottom:4px">
            ${sigDataUrl
              ? '<img src="'+sigDataUrl+'" style="max-height:44px;max-width:180px;object-fit:contain">'
              : '<span style="font-family:\'Brush Script MT\',cursive;font-size:22px;color:#1a2c4a;font-style:italic;opacity:0.4">חתימה...</span>'
            }
          </div>
          <div style="font-size:10px;color:#6b7280;font-weight:700;letter-spacing:0.5px">חתימת המדווח — ${report?.author||''}</div>
        </div>
        <div style="text-align:left">
          <div style="display:inline-block;padding:6px 14px;border:2px solid #1a2c4a;border-radius:4px;transform:rotate(-3deg);margin-bottom:6px">
            <div style="font-size:9px;color:#1a2c4a;font-weight:700;letter-spacing:1px">APPROVED</div>
            <div style="font-size:11px;color:#1a2c4a;font-weight:700;margin-top:1px">YBPROJECTS</div>
          </div>
          <div style="font-size:10px;color:#9ca3af">נחתם דיגיטלית · ${fmtD(report?.createdAt||report?.date)}</div>
        </div>
      </div>
    `;

    // ── יצירת PDF דרך Puppeteer (עם fallback ל-window.print) ──
    YBPPdf.generatePdf({
      orientation: printOrientation,
      logoSrc,
      fileName,
      headerMetaHtml,
      bodyHtml,
      sigHtml,
      projectId: report?.projectId || report?.project || '',
      uploadToDrive: true,
    });
        }}>
          <Icon name="download" size={14}/> תצוגת PDF / הורדה
        </button>
        <button style={{...actionBtnSt, color:'#4338ca', borderColor:'#c7d2fe'}} onClick={() => saveReportToDrive(report)}>
          <svg width="13" height="11" viewBox="0 0 87.3 78" fill="none" style={{flexShrink:0}}>
            <path d="M6.6 66.85l3.85 6.65c.8 1.4 1.95 2.5 3.3 3.3L29.5 48H0c0 1.55.4 3.1 1.2 4.5z" fill="#0066da"/>
            <path d="M43.65 25L29.5 48l16.15 28.8L87.3 48c0-1.55-.4-3.1-1.2-4.5L62.1 4.15c-.8-1.4-1.95-2.5-3.3-3.3z" fill="#00ac47"/>
            <path d="M73.55 76.8c1.35-.8 2.5-1.9 3.3-3.3L79.7 69l4.4-7.55c.8-1.4 1.2-2.95 1.2-4.5H45.65L73.55 76.8z" fill="#ea4335"/>
            <path d="M43.65 25L57.8 2.1C56.45 1.3 54.9.9 53.25.9H34.05c-1.65 0-3.2.4-4.55 1.2z" fill="#00832d"/>
            <path d="M45.65 48H29.5L13.85 76.8c1.35.8 2.9 1.2 4.55 1.2H68.9c1.65 0 3.2-.4 4.55-1.2z" fill="#2684fc"/>
            <path d="M73.4 25.9L59.1.85C58.3-.55 57.15-1.65 55.8-2.45L43.65 25H87.3c0-1.55-.4-3.1-1.2-4.5z" fill="#ffba00"/>
          </svg>
          שמור ב-Drive
        </button>
        <button style={actionBtnSt} onClick={() => onEdit && onEdit(report)}>
          <Icon name="edit" size={14}/> ערוך דוח
        </button>
        <button style={{...actionBtnSt, color:'#dc2626', borderColor:'#fecaca'}} onClick={() => {
          if (window.confirm(`למחוק את הדוח "${report.title}"?\nניתן לשחזר דרך Audit Log (Admin בלבד).`)) {
            const state = SyncStore.get();
            const deleted = (state.reports || []).find(r => r.id === reportId);
            // שמור snapshot לפני מחיקה
            if (deleted && typeof YBP_AUTH !== 'undefined') {
              const session = YBP_AUTH.getSession();
              YBP_AUTH.appendAuditEvent({
                action: 'delete',
                actor: session?.name || 'מנהל',
                detail: `מחק דוח ${deleted.id} — "${deleted.title}"`,
                snapshot: JSON.stringify(deleted),
              });
            }
            state.reports = (state.reports || []).filter(r => r.id !== reportId);
            localStorage.setItem('ybp_sync_store', JSON.stringify(state));
            window.dispatchEvent(new CustomEvent('ybp-sync-change', { detail: state }));
            // v3.9.0.54 — cascade delete גם ל-Supabase
            if (window.deleteReportFromSupabase && reportId) {
              window.deleteReportFromSupabase(reportId).catch(err =>
                console.warn('[deleteReport] Supabase cascade failed:', err.message));
            }
            onBack && onBack();
          }
        }}>
          <Icon name="trash" size={14}/> מחק
        </button>
        {report.driveUrl && (
          <button style={{...actionBtnSt, color:'#047857', borderColor:'#6ee7b7'}}
            onClick={() => window.open(report.driveUrl, '_blank')}>
            📄 PDF
          </button>
        )}
        <div style={{ position:'relative' }}>
          <button style={{...actionBtnSt, background: uploading ? '#6b7280' : '#1d4ed8', color:'#fff', border:'none', opacity: uploading ? 0.7 : 1}}
            onClick={() => !uploading && setShowSendMenu(v => !v)}>
            {uploading ? '📤 מעלה...' : <><Icon name="send" size={14}/> שלח</>}
          </button>
          {showSendMenu && (
            <div style={{
              position:'absolute', top:'calc(100% + 8px)', right:0,
              background:'#fff', borderRadius:10, boxShadow:'0 8px 32px rgba(0,0,0,0.15)',
              border:'1px solid #e5e7eb', minWidth:200, maxWidth:'calc(100vw - 24px)', zIndex:100, overflow:'hidden',
            }}>
              <div style={{ padding:'8px 14px', fontSize:11, color:'#9ca3af', fontWeight:700, borderBottom:'1px solid #f3f4f6', letterSpacing:0.5 }}>שתף דוח</div>
              {/* שלח הכל */}
              <button onClick={async () => {
                setUploading(true); setShowSendMenu(false);
                try {
                  const url = await ensureDriveUrl(report);
                  const txt = buildReportText(report, project, url);
                  const subject = `${report.id} — ${report.title || report.kind}`;
                  const dist = (() => { try { return JSON.parse(localStorage.getItem('ybp_dist_' + report.projectId) || '{}'); } catch { return {}; } })();
                  const waNum = dist.waPhone ? dist.waPhone.replace(/\D/g,'') : '';
                  const emails = dist.emails || '';
                  window.open(waNum
                    ? `https://wa.me/${waNum}?text=${encodeURIComponent(txt)}`
                    : `https://wa.me/?text=${encodeURIComponent(txt)}`, '_blank');
                  setTimeout(() => {
                    window.open(`https://mail.google.com/mail/?view=cm&to=${encodeURIComponent(emails)}&su=${encodeURIComponent(subject)}&body=${encodeURIComponent(txt)}`, '_blank');
                  }, 300);
                } finally { setUploading(false); }
              }} style={{
                width:'100%', padding:'11px 14px', background:'#1a2c4a', border:'none',
                cursor:'pointer', display:'flex', alignItems:'center', gap:10,
                fontSize:14, fontFamily:'inherit', textAlign:'right', direction:'rtl',
              }}>
                <span style={{ fontSize:18 }}>🚀</span>
                <div style={{ textAlign:'right' }}>
                  <div style={{ fontWeight:700, color:'#fff' }}>שלח הכל</div>
                  <div style={{ fontSize:11, color:'rgba(255,255,255,0.7)' }}>WhatsApp + Gmail + קישור PDF</div>
                </div>
              </button>
              <button onClick={async () => {
                setUploading(true); setShowSendMenu(false);
                try {
                  const url = await ensureDriveUrl(report);
                  const txt = buildReportText(report, project, url);
                  const dist = (() => { try { return JSON.parse(localStorage.getItem('ybp_dist_' + report.projectId) || '{}'); } catch { return {}; } })();
                  const waNum = dist.waPhone ? dist.waPhone.replace(/\D/g,'') : '';
                  window.open(waNum
                    ? `https://wa.me/${waNum}?text=${encodeURIComponent(txt)}`
                    : `https://wa.me/?text=${encodeURIComponent(txt)}`, '_blank');
                } finally { setUploading(false); }
              }} style={{
                width:'100%', padding:'11px 14px', background:'transparent', border:'none',
                cursor:'pointer', display:'flex', alignItems:'center', gap:10,
                fontSize:14, fontFamily:'inherit', textAlign:'right', direction:'rtl',
                borderTop:'1px solid #f3f4f6',
              }}>
                <span style={{ fontSize:18 }}>💬</span>
                <div style={{ textAlign:'right' }}>
                  <div style={{ fontWeight:700, color:'#1f2937' }}>WhatsApp בלבד</div>
                  <div style={{ fontSize:11, color:'#6b7280' }}>{ (() => { try { const d=JSON.parse(localStorage.getItem('ybp_dist_'+report.projectId)||'{}'); return d.waPhone||'מספר לא מוגדר'; } catch{return 'מספר לא מוגדר';} })() }</div>
                </div>
              </button>
              <button onClick={async () => {
                setUploading(true); setShowSendMenu(false);
                try {
                  const url = await ensureDriveUrl(report);
                  const txt = buildReportText(report, project, url);
                  const subject = `${report.id} — ${report.title || report.kind}`;
                  const dist = (() => { try { return JSON.parse(localStorage.getItem('ybp_dist_' + report.projectId) || '{}'); } catch { return {}; } })();
                  const emails = dist.emails || '';
                  window.open(`https://mail.google.com/mail/?view=cm&to=${encodeURIComponent(emails)}&su=${encodeURIComponent(subject)}&body=${encodeURIComponent(txt)}`, '_blank');
                } finally { setUploading(false); }
              }} style={{
                width:'100%', padding:'11px 14px', background:'transparent', border:'none',
                cursor:'pointer', display:'flex', alignItems:'center', gap:10,
                fontSize:14, fontFamily:'inherit', textAlign:'right', direction:'rtl',
                borderTop:'1px solid #f3f4f6',
              }}>
                <span style={{ fontSize:18 }}>✉️</span>
                <div style={{ textAlign:'right' }}>
                  <div style={{ fontWeight:700, color:'#1f2937' }}>Gmail בלבד</div>
                  <div style={{ fontSize:11, color:'#6b7280' }}>{ (() => { try { const d=JSON.parse(localStorage.getItem('ybp_dist_'+report.projectId)||'{}'); return d.emails||'מיילים לא מוגדרים'; } catch{return 'מיילים לא מוגדרים';} })() }</div>
                </div>
              </button>
              {/* הגדרת נמענים */}
              <button onClick={() => {
                const dist = (() => { try { return JSON.parse(localStorage.getItem('ybp_dist_' + report.projectId) || '{}'); } catch { return {}; } })();
                const phone = window.prompt('מספר WhatsApp לשליחת דוחות (כולל קידומת מדינה, למשל 972501234567):', dist.waPhone || '');
                if (phone === null) return;
                const emails = window.prompt('מיילים לשליחה (מופרדים בפסיק):', dist.emails || '');
                if (emails === null) return;
                localStorage.setItem('ybp_dist_' + report.projectId, JSON.stringify({ waPhone: phone.trim(), emails: emails.trim() }));
                setShowSendMenu(false);
              }} style={{
                width:'100%', padding:'10px 14px', background:'transparent', border:'none',
                cursor:'pointer', display:'flex', alignItems:'center', gap:10,
                fontSize:12, fontFamily:'inherit', textAlign:'right', direction:'rtl',
                borderTop:'1px solid #f3f4f6', color:'#6b7280',
              }}>
                <span style={{ fontSize:15 }}>⚙️</span> הגדר נמענים לפרויקט
              </button>
            </div>
          )}
        </div>
      </header>

      {/* Document — A4 paper */}
      <div style={{ maxWidth: 820, margin:'0 auto', padding: isMobile ? '12px 8px 40px' : '28px 16px 40px' }}>
        <div className="ybp-doc" style={{
          background:'#fff', boxShadow:'0 4px 24px rgba(15,23,42,0.08), 0 1px 2px rgba(15,23,42,0.06)',
          borderRadius:2, position:'relative',
          padding:'0 0 0', overflow:'hidden',
        }}>

          {/* Watermark */}
          <div style={{
            position:'absolute', top:'50%', left:'50%',
            transform:'translate(-50%, -50%)',
            fontSize:220, fontWeight:900, color:'rgba(26,44,74,0.045)',
            fontFamily:'Georgia, serif', letterSpacing:20,
            pointerEvents:'none', userSelect:'none', zIndex:0,
            lineHeight:1,
          }}>YBP</div>

          {/* ═══ LETTERHEAD HEADER ═══ */}
          {/* Gray background band */}
          <div style={{
            background:'#ebebeb',
            padding:'16px 0 0',
            display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center',
          }}>
            <img src="assets/ybp-logo-new.png" alt="YBP" style={{
              height:90, display:'block', objectFit:'contain',
            }}/>
          </div>
          {/* Gradient separator lines: gold + navy */}
          <div style={{ height:3, background:'linear-gradient(to left, transparent 0%, #b5a882 30%, #b5a882 70%, transparent 100%)', marginTop:-8 }}/>
          <div style={{ height:2.5, background:'linear-gradient(to left, transparent 0%, #1a2c4a 30%, #1a2c4a 70%, transparent 100%)' }}/>

          {/* Report type badge + ID — below header */}
          <div style={{
            padding: isMobile ? '12px 14px' : '16px 56px 12px',
            display:'flex', alignItems:'center', justifyContent:'space-between',
            borderBottom:'1px solid #e8e8e8', position:'relative', zIndex:1,
          }}>
            <div style={{ display:'flex', alignItems:'center', gap:10 }}>
              <div style={{
                display:'inline-block', padding:'4px 12px', borderRadius:2,
                background:'#1a2c4a', color:'#fff',
                fontSize:10, fontWeight:700, letterSpacing:1.2,
              }}>{({ daily:'DAILY REPORT', weekly:'WEEKLY REPORT', rejects:'REJECTS REPORT', infra:'INFRA REPORT' })[report.kind] || 'REPORT'}</div>
            </div>
            <div style={{ textAlign:'left' }}>
              <div style={{
                fontFamily:'ui-monospace, Menlo, monospace', fontSize:13, fontWeight:700,
                color:'#1a2c4a', letterSpacing:0.5,
              }}>{report.id}</div>
              <div style={{ fontSize:11, color:'#9ca3af', marginTop:2 }}>{fmtDateHe(report.date)}</div>
            </div>
          </div>

          {/* Title block */}
          <div style={{ padding: isMobile ? '14px 14px 0' : '20px 56px 0', position:'relative', zIndex:1 }}>
            <h1 style={{
              margin:0, fontSize:26, fontWeight:700, color:'#0f1e38', lineHeight:1.2,
            }}>{report.title}</h1>
            {project?.name && (
              <div style={{ fontSize:14, color:'#6b7280', marginTop:6 }}>
                פרויקט: <strong style={{ color:'#1f2937' }}>{project.name}</strong>
                {project.address && <span> · {project.address}</span>}
              </div>
            )}
          </div>

          {/* Content */}
          <div style={{ padding: isMobile ? '16px 14px 24px' : '24px 56px 32px', display:'flex', flexDirection:'column', gap:24, position:'relative', zIndex:1 }}>

            {/* Metadata bar */}
            <div style={{
              display:'grid', gridTemplateColumns: isMobile ? '1fr 1fr' : 'repeat(3, 1fr)', gap:16,
              padding:'14px 16px', background:'#f9fafb', borderRadius:4,
              border:'1px solid #e5e7eb',
            }}>
              <MetaItem label="תאריך" value={fmtDateHe(report.date)}/>
              <MetaItem label="נוצר על ידי" value={report.author}/>
              <MetaItem label="סטטוס" value={report.kind === 'daily' && statusOpt ? statusOpt.label : 'נשלח'}/>
            </div>

            {/* ── Weekly-specific sections ─────────────────────────────── */}
            {report.kind === 'weekly' && (
              <>
                {/* KPIs */}
                <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:12 }}>
                  {[
                    { label:'ימי עבודה', value: c.totalWorkDays ?? 0 },
                    { label:'ימי עיכוב',  value: c.delayDays ?? 0 },
                    { label:"ריג'קטים",   value: report.rejects?.length ?? 0 },
                  ].map(({ label, value }) => (
                    <div key={label} style={{
                      background:'#f9fafb', borderRadius:8, padding:'14px 16px',
                      textAlign:'center', border:'1px solid #e5e7eb',
                    }}>
                      <div style={{ fontSize:28, fontWeight:800, color:'#1a2c4a' }}>{value}</div>
                      <div style={{ fontSize:11, color:'#6b7280', marginTop:2 }}>{label}</div>
                    </div>
                  ))}
                </div>

                {/* Contractors */}
                {c.contractors?.length > 0 && (
                  <div>
                    <SectionLabel>קבלנים פעילים השבוע</SectionLabel>
                    <div style={{ display:'flex', flexWrap:'wrap', gap:6 }}>
                      {c.contractors.map(co => (
                        <div key={co.trade} style={{
                          padding:'6px 12px', borderRadius:16, background:'#eff6ff',
                          color:'#1d4ed8', fontSize:13, fontWeight:600, border:'1px solid #dbeafe',
                        }}>
                          {co.trade}
                          {co.days && <span style={{ opacity:0.6, fontSize:11, marginRight:4 }}>({co.days} ימים)</span>}
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {/* Issues from daily reports */}
                {c.issues?.length > 0 && (
                  <div>
                    <SectionLabel>בעיות שעלו השבוע</SectionLabel>
                    <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
                      {c.issues.map((iss, i) => (
                        <div key={i} style={{
                          padding:'8px 12px', background:'#fef3c7', borderRadius:6,
                          borderRight:'3px solid #d97706', fontSize:12, color:'#713f12',
                        }}>
                          <span style={{ fontWeight:700, color:'#6b7280' }}>{fmtDateHe(iss.date)}: </span>
                          {iss.text}
                        </div>
                      ))}
                    </div>
                  </div>
                )}

                {/* Highlights */}
                {c.highlights && (
                  <div>
                    <SectionLabel>נקודות בולטות השבוע</SectionLabel>
                    <div style={{
                      padding:'12px 16px', background:'#f0fdf4', borderRadius:8,
                      fontSize:13, color:'#14532d', lineHeight:1.8, whiteSpace:'pre-wrap',
                      borderRight:'3px solid #22c55e',
                    }}>{c.highlights}</div>
                  </div>
                )}

                {/* Summary */}
                {c.summary && (
                  <div>
                    <SectionLabel>סיכום שבוע</SectionLabel>
                    <div style={{
                      padding:'12px 16px', background:'#f9fafb', borderRadius:8,
                      fontSize:13, color:'#374151', lineHeight:1.7, whiteSpace:'pre-wrap',
                      border:'1px solid #e5e7eb',
                    }}>{c.summary}</div>
                  </div>
                )}

                {/* Next week */}
                {c.nextWeek && (
                  <div>
                    <SectionLabel>תחזית שבוע הבא</SectionLabel>
                    <div style={{
                      padding:'12px 16px', background:'#eff6ff', borderRadius:8,
                      fontSize:13, color:'#1e3a5f', lineHeight:1.8, whiteSpace:'pre-wrap',
                      borderRight:'3px solid #3b82f6',
                    }}>{c.nextWeek}</div>
                  </div>
                )}
              </>
            )}

            {/* Daily-specific: day status */}
            {report.kind === 'daily' && c.dayStatus && (
              <div>
                <SectionLabel>סטטוס יום</SectionLabel>
                <div style={{ display:'flex', alignItems:'center', gap:10 }}>
                  <span style={{
                    display:'inline-block', width:8, height:8, borderRadius:8,
                    background: statusOpt?.color,
                  }}/>
                  <span style={{ fontSize:14, fontWeight:600, color:'#1f2937' }}>
                    {statusOpt?.label}
                  </span>
                  {c.statusReason && (
                    <span style={{ fontSize:13, color:'#6b7280' }}>— {c.statusReason}</span>
                  )}
                </div>
              </div>
            )}

            {/* Contractors on site */}
            {c.contractors?.length > 0 && (
              <div>
                <SectionLabel>קבלנים באתר ({c.contractors.length})</SectionLabel>
                <div style={{ display:'flex', flexWrap:'wrap', gap:6 }}>
                  {c.contractors.map(co => (
                    <div key={co.trade} style={{
                      padding:'6px 12px', borderRadius:16, background:'#eff6ff',
                      color:'#1d4ed8', fontSize:13, fontWeight:600, border:'1px solid #dbeafe',
                      display:'flex', alignItems:'center', gap:6,
                    }}>
                      {co.trade}
                      {co.count && <span style={{ opacity:0.7, fontSize:11 }}>× {co.count}</span>}
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Progress */}
            {c.progress?.length > 0 && (
              <div>
                <SectionLabel>התקדמות — משימות שקודמו</SectionLabel>
                <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
                  {c.progress.map(p => (
                    <div key={p.taskId} style={{
                      display:'flex', alignItems:'center', gap:10, padding:'8px 12px',
                      background:'#fafbfc', borderRadius:6,
                    }}>
                      <Icon name="check" size={14} color="#10b981"/>
                      <div style={{ flex:1, fontSize:13, color:'#1f2937' }}>{p.title}</div>
                      <div style={{ fontSize:12, fontWeight:700, color:'#1d4ed8' }}>{p.percentDone}%</div>
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Rejects — table on desktop, cards on mobile */}
            {report.rejects?.length > 0 && (
              <div>
                <SectionLabel>ריג׳קטים ({report.rejects.length})</SectionLabel>
                {isMobile ? (
                  <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
                    {report.rejects.map((r, i) => {
                      const photos = r.photos || (r.photo ? [r.photo] : []);
                      const sevColor = { critical:'#dc2626', high:'#f97316', medium:'#f59e0b', low:'#6b7280' }[r.severity] || '#6b7280';
                      return (
                        <div key={r.id} style={{ background:'#fff', border:'1px solid #e5e7eb', borderRight:`4px solid ${sevColor}`, borderRadius:8, padding:'12px 14px' }}>
                          <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:6 }}>
                            <span style={{ fontSize:11, fontWeight:800, color:'#1a2c4a', background:'#f3f4f6', borderRadius:4, padding:'2px 7px', flexShrink:0 }}>{i+1}</span>
                            <span style={{ fontSize:13, fontWeight:700, color:'#1f2937', flex:1 }}>{r.title}</span>
                          </div>
                          {r.description && <div style={{ fontSize:12, color:'#4b5563', lineHeight:1.5, marginBottom:6 }}>{r.description}</div>}
                          <div style={{ display:'flex', gap:12, flexWrap:'wrap', fontSize:11, color:'#6b7280' }}>
                            {r.assignee && <span>👤 {r.assignee}</span>}
                            {r.due && <span>📅 {fmtDateHe(r.due)}</span>}
                            <span style={{ color:'#9ca3af' }}>🔒 {fmtDateHe(r.createdAt || report.date)}</span>
                          </div>
                          {photos.length > 0 && (
                            <div style={{ display:'flex', flexWrap:'wrap', gap:6, marginTop:8 }}>
                              {photos.map((ph,pi) => (
                                <img key={pi} src={ph} alt={`תמונה ${pi+1}`}
                                  style={{ width:72, height:72, objectFit:'cover', borderRadius:6, border:'1px solid #e5e7eb' }}/>
                              ))}
                            </div>
                          )}
                        </div>
                      );
                    })}
                  </div>
                ) : (
                  <table style={{ width:'100%', borderCollapse:'collapse', fontSize:11 }}>
                    <thead>
                      <tr style={{ background:'#1a2c4a', color:'#fff' }}>
                        {["מס'","ממצא ריג'קט","תיאור","אחראי","תאריך יעד","תאריך ממצא 🔒","תמונות"].map(h => (
                          <th key={h} style={{ padding:'9px 8px', textAlign:'right', fontWeight:700, color:'#fff', fontSize:10, letterSpacing:0.4, border:'1px solid #14213a', whiteSpace:'nowrap' }}>{h}</th>
                        ))}
                      </tr>
                    </thead>
                    <tbody>
                      {report.rejects.map((r, i) => {
                        const photos = r.photos || (r.photo ? [r.photo] : []);
                        return (
                          <tr key={r.id} style={{ background: i%2 ? '#f8f9fa' : '#fff', verticalAlign:'top' }}>
                            <td style={{ padding:'9px 8px', textAlign:'center', fontWeight:700, color:'#1a2c4a', width:28, border:'1px solid #e5e7eb' }}>{i+1}</td>
                            <td style={{ padding:'9px 8px', fontWeight:600, color:'#1f2937', minWidth:110, border:'1px solid #e5e7eb', lineHeight:1.3 }}>{r.title}</td>
                            <td style={{ padding:'9px 8px', fontSize:10.5, color:'#4b5563', minWidth:140, border:'1px solid #e5e7eb', lineHeight:1.5 }}>{r.description || '—'}</td>
                            <td style={{ padding:'9px 8px', fontSize:11, whiteSpace:'nowrap', border:'1px solid #e5e7eb' }}>{r.assignee || '—'}</td>
                            <td style={{ padding:'9px 8px', fontSize:11, fontWeight:600, color:'#1a2c4a', whiteSpace:'nowrap', border:'1px solid #e5e7eb' }}>{fmtDateHe(r.due) || '—'}</td>
                            <td style={{ padding:'9px 8px', fontSize:10.5, color:'#9ca3af', whiteSpace:'nowrap', border:'1px solid #e5e7eb' }}>{fmtDateHe(r.createdAt || report.date)}</td>
                            <td style={{ padding:'7px 8px', border:'1px solid #e5e7eb', minWidth:110 }}>
                              <div style={{ display:'flex', flexDirection:'column', gap:3 }}>
                                {photos.map((ph,pi) => (
                                  <img key={pi} src={ph} alt={`תמונה ${pi+1}`}
                                    style={{ width:'100%', maxWidth:110, height:'auto', display:'block', borderRadius:3, border:'1px solid #d1d5db' }}/>
                                ))}
                                {photos.length===0 && <span style={{ fontSize:10, color:'#d1d5db' }}>—</span>}
                              </div>
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                )}
              </div>
            )}

            {/* Issues */}
            {c.issues && (
              <div>
                <SectionLabel>בעיות ואבני דרך</SectionLabel>
                <div style={{
                  padding:'12px 16px', background:'#fef3c7', borderRadius:8,
                  fontSize:13, color:'#713f12', lineHeight:1.6, whiteSpace:'pre-wrap',
                  borderRight:'3px solid #d97706',
                }}>{c.issues}</div>
              </div>
            )}

            {/* Suppliers */}
            {c.suppliers?.length > 0 && (
              <div>
                <SectionLabel>ספקים / חומרים שהגיעו</SectionLabel>
                <table style={tableSt}>
                  <thead>
                    <tr>
                      <th style={thSt}>ספק</th>
                      <th style={thSt}>פריט</th>
                      <th style={thSt}>הערה</th>
                    </tr>
                  </thead>
                  <tbody>
                    {c.suppliers.map((s, i) => (
                      <tr key={i}>
                        <td style={tdSt}>{s.name}</td>
                        <td style={tdSt}>{s.item}</td>
                        <td style={{ ...tdSt, color:'#6b7280' }}>{s.note || '—'}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}

            {/* Visits */}
            {c.visits?.length > 0 && (
              <div>
                <SectionLabel>ביקורים באתר</SectionLabel>
                <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
                  {c.visits.map((v, i) => (
                    <div key={i} style={{
                      display:'flex', alignItems:'center', gap:10, padding:'8px 12px',
                      background:'#fafbfc', borderRadius:6, fontSize:13,
                    }}>
                      <Icon name="users" size={14} color="#6b7280"/>
                      <strong style={{ color:'#1f2937' }}>{v.name}</strong>
                      {v.role && <span style={{ color:'#6b7280' }}>· {v.role}</span>}
                    </div>
                  ))}
                </div>
              </div>
            )}

            {/* Notes */}
            {c.notes && (
              <div>
                <SectionLabel>הערות</SectionLabel>
                <div style={{ fontSize:13, color:'#4b5563', lineHeight:1.6, whiteSpace:'pre-wrap' }}>
                  {c.notes}
                </div>
              </div>
            )}

            {/* Infra items */}
            {report.kind === 'infra' && c.items?.length > 0 && (() => {
              const STATUS_COLORS = { ok:{color:'#10b981',bg:'#d1fae5',label:'תקין'}, issue:{color:'#f59e0b',bg:'#fef3c7',label:'טעון טיפול'}, critical:{color:'#dc2626',bg:'#fee2e2',label:'בעיה קריטית'} };
              const INFRA_ICONS = { foundation:'🏗️',envelope:'🧱',plumbing:'🔧',electric:'⚡',lowvoltage:'📡',gas:'🔥',hvac:'❄️',fire:'🚿',plaster:'🪣',flooring:'⬜',facade:'🏢',drainage:'🌊',insulation:'🛡️',other:'📋' };
              const INFRA_LABELS = { foundation:'יסודות ושלד',envelope:'מעטפת',plumbing:'אינסטלציה',electric:'חשמל',lowvoltage:'מתח נמוך / תקשורת',gas:'גז',hvac:'מיזוג אוויר',fire:'אש וגילוי עשן',plaster:'טיח וגבס',flooring:'ריצוף ואריחים',facade:'חזיתות',drainage:'ניקוז וביוב',insulation:'איטום',other:'אחר' };
              return (
                <div>
                  <SectionLabel>סעיפי תשתית ({c.items.length})</SectionLabel>
                  <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
                    {c.items.map((item, i) => {
                      const st = STATUS_COLORS[item.status] || STATUS_COLORS.ok;
                      const photos = item.photos || [];
                      return (
                        <div key={item.id || i} style={{ border:`1px solid ${st.color}`, borderRight:`4px solid ${st.color}`, borderRadius:8, overflow:'hidden' }}>
                          <div style={{ display:'flex', alignItems:'center', gap:8, padding:'9px 12px', background:st.bg }}>
                            <span style={{ width:22, height:22, borderRadius:5, background:'rgba(255,255,255,0.7)', display:'flex', alignItems:'center', justifyContent:'center', fontSize:11, fontWeight:800, flexShrink:0 }}>{i+1}</span>
                            <span style={{ fontSize:16 }}>{INFRA_ICONS[item.infraType] || '📋'}</span>
                            <span style={{ flex:1, fontSize:13, fontWeight:700, color:'#1f2937' }}>{INFRA_LABELS[item.infraType] || item.infraType}</span>
                            {item.location && <span style={{ fontSize:11, color:'#6b7280' }}>📍 {item.location}</span>}
                            <span style={{ fontSize:10, fontWeight:700, padding:'2px 8px', borderRadius:10, background:'rgba(255,255,255,0.7)', color:st.color }}>{st.label}</span>
                          </div>
                          {item.description && (
                            <div style={{ padding:'10px 12px', fontSize:12.5, color:'#374151', lineHeight:1.5, borderBottom: photos.length ? '1px solid #f3f4f6' : 'none' }}>{item.description}</div>
                          )}
                          {photos.length > 0 && (
                            <div style={{ padding:'10px 12px', display:'flex', flexWrap:'wrap', gap:6 }}>
                              {photos.map((ph,pi) => (
                                <img key={pi} src={ph} alt="" style={{ width:90, height:90, objectFit:'cover', borderRadius:6, border:'1px solid #e5e7eb' }}/>
                              ))}
                            </div>
                          )}
                        </div>
                      );
                    })}
                  </div>
                </div>
              );
            })()}

          </div>

          {/* Signature footer — A4 style */}
          <div style={{
            padding: isMobile ? '20px 14px 16px' : '28px 56px 20px', borderTop:'1px solid #e5e7eb',
            display:'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: isMobile ? 20 : 40,
            position:'relative', zIndex:1,
          }}>
            <div>
              <div style={{
                height:48, borderBottom:'1px solid #1a2c4a', marginBottom:8,
                display:'flex', alignItems:'flex-end', paddingBottom:4,
              }}>
                {sigDataUrl
                  ? <img src={sigDataUrl} style={{ maxHeight:44, maxWidth:180, objectFit:'contain' }}/>
                  : <span style={{ fontFamily:'"Brush Script MT", cursive', fontSize:22, color:'#1a2c4a', fontStyle:'italic', opacity:0.4 }}>חתימה...</span>
                }
              </div>
              <div style={{ fontSize:10, color:'#6b7280', fontWeight:700, letterSpacing:0.5, display:'flex', alignItems:'center', gap:8 }}>
                חתימת המדווח — {report.author}
                <button onClick={() => setShowSigPad(true)} style={{
                  padding:'2px 8px', borderRadius:4, border:'1px solid #1a2c4a',
                  background:'transparent', color:'#1a2c4a', fontSize:10, fontWeight:700,
                  cursor:'pointer', fontFamily:'inherit',
                }}>✍️ חתום</button>
                {sigDataUrl && <button onClick={() => { setSigDataUrl(null); localStorage.removeItem('ybp_sig_'+reportId); }} style={{
                  padding:'2px 6px', borderRadius:4, border:'1px solid #e5e7eb',
                  background:'transparent', color:'#9ca3af', fontSize:10, cursor:'pointer', fontFamily:'inherit',
                }}>מחק</button>}
              </div>
            </div>
            <div style={{ textAlign:'left' }}>
              <div style={{
                display:'inline-block', padding:'6px 14px', border:'2px solid #1a2c4a',
                borderRadius:4, transform:'rotate(-3deg)', marginBottom:6,
              }}>
                <div style={{ fontSize:9, color:'#1a2c4a', fontWeight:700, letterSpacing:1 }}>APPROVED</div>
                <div style={{ fontSize:11, color:'#1a2c4a', fontWeight:700, marginTop:1 }}>YBPROJECTS</div>
              </div>
              <div style={{ fontSize:10, color:'#9ca3af' }}>
                נחתם דיגיטלית · {fmtDateHe(report.createdAt || report.date)}
              </div>
            </div>
          </div>

          {/* Footer strip — matches YBP letterhead: beige band + navy accent */}
          {/* Footer — approved YBP letterhead */}
          <div>
            <div style={{
              padding:'14px 52px', background:'#c8bfa8', color:'#4a3f2f',
              textAlign:'center', fontSize:10.5, letterSpacing:0.3, lineHeight:1.7,
            }}>
              <div style={{ fontWeight:700 }}>YBPROJECTS · ניהול פרויקטים בבנייה</div>
              <div style={{ fontWeight:400, fontSize:10 }}>זרחין 10, רעננה</div>
              <div style={{ fontWeight:400, fontSize:10 }}>yuval@ybprojects.com · office@ybprojects.com</div>
            </div>
            <div style={{ height:4, background:'linear-gradient(to left, transparent 0%, #1a2c4a 30%, #1a2c4a 70%, transparent 100%)' }}/>
            <div style={{ height:10, background:'#fff' }}/>
          </div>
        </div>

        {/* Back to project */}
        <div style={{ textAlign:'center', marginTop:20, marginBottom:20 }} className="no-print">
          <button onClick={onBack} style={{
            padding:'9px 20px', background:'#fff', border:'1px solid #e5e7eb', borderRadius:6,
            color:'#6b7280', fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:'inherit',
          }}>חזרה לפרויקט</button>
        </div>
      </div>
    </div>
  );
};

const SectionLabel = ({ children }) => (
  <div style={{
    fontSize:11, fontWeight:700, color:'#6b7280', letterSpacing:0.5,
    marginBottom:10, textTransform:'uppercase',
  }}>{children}</div>
);

const MetaItem = ({ label, value }) => (
  <div>
    <div style={{ fontSize:10, color:'#9ca3af', fontWeight:600, letterSpacing:0.3, marginBottom:2 }}>
      {label.toUpperCase()}
    </div>
    <div style={{ fontSize:13, fontWeight:600, color:'#1f2937' }}>{value}</div>
  </div>
);

const actionBtnSt = {
  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,
};
const tableSt = {
  width:'100%', borderCollapse:'collapse', fontSize:13,
};
const thSt = {
  padding:'8px 10px', textAlign:'right', fontSize:11, fontWeight:700, color:'#6b7280',
  background:'#fafbfc', borderBottom:'1px solid #e5e7eb', letterSpacing:0.3,
};
const tdSt = {
  padding:'10px', borderBottom:'1px solid #f3f4f6', color:'#1f2937',
};

window.ReportViewer = ReportViewer;

// Inject print styles once
if (!document.getElementById('ybp-print-styles')) {
  const s = document.createElement('style');
  s.id = 'ybp-print-styles';
  s.textContent = `
    @media print {
      @page {
        size: A4;
        margin-top: 115px;
        margin-bottom: 64px;
        margin-left: 20mm;
        margin-right: 20mm;
      }
      .sidebar, .nav-buttons, .action-bar, .toolbar, button, .no-print { display: none !important; }
      .print-header {
        position: fixed;
        top: -115px;
        left: 0; right: 0;
        height: 115px;
      }
      .print-footer {
        position: fixed;
        bottom: -64px;
        left: 0; right: 0;
        height: 64px;
      }
      section, .section, .block, .card, .finding, table, tr, img, figure {
        page-break-inside: avoid;
        break-inside: avoid;
      }
      h1, h2, h3, h4 { page-break-after: avoid; break-after: avoid; }
      body {
        margin-top: 115px;
        margin-bottom: 64px;
        background: #fff !important;
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
      }
      .ybp-doc { box-shadow: none !important; border-radius: 0 !important; }
    }
  `;
  document.head.appendChild(s);
}

})();
