// Project Booklet — חוברת פרויקט
// Checklist of all milestone items throughout project lifecycle
(function(){
const { useState, useEffect } = React;

const BOOKLET_STORAGE = 'ybp_booklet_';

// Default booklet structure — matches the platform's existing booklet

// Add N business days (skip Fri=5, Sat=6 in Israel)
const addBusinessDays = (startISO, days) => {
  const d = new Date(startISO + 'T00:00:00');
  let added = 0;
  while (added < days) {
    d.setDate(d.getDate() + 1);
    const dow = d.getDay();
    if (dow !== 5 && dow !== 6) added++;
  }
  return d.toISOString().slice(0, 10);
};

// Build booklet items with due dates based on project start
const buildBookletItems = (projectStart) => {
  const s = projectStart || new Date().toISOString().slice(0, 10);
  return [
    // Stage 1 — פתיחת פרויקט
    { id: 'client-details',   stage: '1', stageLabel: 'פתיחת פרויקט',    title: 'דף פרטי לקוח',             description: 'מילוי פרטי לקוח מלאים — שם, כתובת, ת.ז, אמצעי קשר, תנאי תשלום', type: 'form',      formScreen: 'clientDetails', required: true,  order: 1,  defaultDue: addBusinessDays(s, 3)   },
    { id: 'infra-survey',     stage: '1', stageLabel: 'פתיחת פרויקט',    title: 'סקר תשתיות',               description: 'בדיקת תשתיות קיימות — חשמל, אינסטלציה, מיזוג, מבנה',            type: 'report',    formScreen: 'infraSurvey',   required: true,  order: 2,  defaultDue: addBusinessDays(s, 5)   },
    { id: 'permits',          stage: '1', stageLabel: 'פתיחת פרויקט',    title: 'היתרי בנייה ורישוי',       description: 'הגשת בקשה להיתר, מעקב אישור',                                    type: 'checklist', required: true,  order: 3,  defaultDue: addBusinessDays(s, 10)  },
    { id: 'insurance',        stage: '1', stageLabel: 'פתיחת פרויקט',    title: 'ביטוחים',                  description: 'ביטוח עבודות, ביטוח צד ג׳, ביטוח קבלנים',                       type: 'document',  required: true,  order: 4,  defaultDue: addBusinessDays(s, 14)  },
    // Stage 2 — תכנון
    { id: 'arch-plans',       stage: '2', stageLabel: 'תכנון',            title: 'תוכניות אדריכל',           description: 'קבלת תוכניות מהאדריכל — העמדה, חתכים, ריצוף, תקרות, גמרים',   type: 'document',  required: true,  order: 5,  defaultDue: addBusinessDays(s, 21)  },
    { id: 'kitchen-plans',    stage: '2', stageLabel: 'תכנון',            title: 'תוכניות מטבח',             description: 'קבלת תוכניות ממתכנן המטבח (אם רלוונטי)',                         type: 'document',  required: false, order: 6,  defaultDue: addBusinessDays(s, 25)  },
    { id: 'consultant-plans', stage: '2', stageLabel: 'תכנון',            title: 'תוכניות יועצים',           description: 'חשמל, אינסטלציה, מיזוג, בטיחות, נגישות',                        type: 'document',  required: true,  order: 7,  defaultDue: addBusinessDays(s, 30)  },
    { id: 'budget-approved',  stage: '2', stageLabel: 'תכנון',            title: 'תקציב מאושר',              description: 'אישור תקציב מהלקוח בחתימה',                                      type: 'document',  required: true,  order: 8,  defaultDue: addBusinessDays(s, 35)  },
    // Stage 3 — קבלנים וספקים
    { id: 'main-contractor',  stage: '3', stageLabel: 'קבלנים וספקים',   title: 'חוזה קבלן ראשי',           description: 'חתימת חוזה עם קבלן ראשי',                                        type: 'document',  required: true,  order: 9,  defaultDue: addBusinessDays(s, 45)  },
    { id: 'subcontractors',   stage: '3', stageLabel: 'קבלנים וספקים',   title: 'חוזי קבלני משנה',          description: 'חשמל, אינסטלציה, מיזוג, גמרים',                                  type: 'checklist', required: true,  order: 10, defaultDue: addBusinessDays(s, 50)  },
    { id: 'suppliers',        stage: '3', stageLabel: 'קבלנים וספקים',   title: 'הזמנות ספקים עיקריים',     description: 'ריהוט, מטבח, תאורה, ריצוף',                                      type: 'checklist', required: false, order: 11, defaultDue: addBusinessDays(s, 55)  },
    // Stage 4 — ביצוע בשטח (חדש)
    { id: 'safety-briefing',  stage: '4', stageLabel: 'ביצוע בשטח',      title: 'ברייפינג בטיחות',          description: 'הדרכת כל העובדים לפני תחילת עבודה',                              type: 'checklist', required: true,  order: 12, defaultDue: addBusinessDays(s, 60)  },
    { id: 'safety-equipment', stage: '4', stageLabel: 'ביצוע בשטח',      title: 'ציוד בטיחות באתר',         description: 'מטפים, שילוט, ציוד מגן',                                         type: 'checklist', required: true,  order: 13, defaultDue: addBusinessDays(s, 60)  },
    { id: 'gantt-exec',       stage: '4', stageLabel: 'ביצוע בשטח',      title: 'גאנט ביצוע',               description: 'לוח זמנים מפורט של ביצוע העבודות בשטח',                         type: 'gantt',     required: false, order: 14, defaultDue: null                    },
    // Stage 5 — סיום ומסירה
    { id: 'municipality-approval', stage: '5', stageLabel: 'סיום ומסירה', title: 'אישור עירייה / עוצמות',  description: 'קבלת אישורי סיום מהרשויות',                                       type: 'document',  required: true,  order: 15, defaultDue: addBusinessDays(s, 120) },
    { id: 'fire-approval',    stage: '5', stageLabel: 'סיום ומסירה',      title: 'אישור כיבוי אש',           description: 'אישור מכבי האש לפתיחה',                                          type: 'document',  required: true,  order: 16, defaultDue: addBusinessDays(s, 120) },
    { id: 'as-made',          stage: '5', stageLabel: 'סיום ומסירה',      title: 'תוכניות AS MADE',          description: 'תוכניות כפי שבוצע בפועל',                                        type: 'document',  required: true,  order: 17, defaultDue: addBusinessDays(s, 125) },
    { id: 'client-handover',  stage: '5', stageLabel: 'סיום ומסירה',      title: 'פרוטוקול מסירה ללקוח',    description: 'חתימת פרוטוקול מסירה עם הלקוח',                                  type: 'document',  required: true,  order: 18, defaultDue: addBusinessDays(s, 130) },
  ];
};

const DEFAULT_BOOKLET_ITEMS = buildBookletItems(new Date().toISOString().slice(0,10));

function loadBooklet(projectId) {
  const project = YBP_DATA.projects.find(p => p.id === projectId);
  const projectStart = project?.startDate || new Date().toISOString().slice(0,10);
  const defaultItems = buildBookletItems(projectStart);
  try {
    const raw = localStorage.getItem(BOOKLET_STORAGE + projectId);
    if (raw) {
      const saved = JSON.parse(raw);
      return defaultItems.map(item => ({
        ...item,
        ...(saved[item.id] || {}),
      }));
    }
  } catch(e) {}
  return defaultItems.map(item => ({ ...item, completed: false, completedAt: null, completedBy: null, notes: '' }));
}

function saveBooklet(projectId, items) {
  const state = {};
  items.forEach(item => {
    state[item.id] = { completed: item.completed, completedAt: item.completedAt, completedBy: item.completedBy, notes: item.notes };
  });
  localStorage.setItem(BOOKLET_STORAGE + projectId, JSON.stringify(state));
}

// סימון פריט בחוברת כהושלם — נקרא מתוך טפסי החוברת בלחיצה על "אשר וסמן כהושלם"
function markBookletItemComplete(projectId, itemId) {
  if (!projectId || !itemId) return;
  const who = ((window.YBP_AUTH && window.YBP_AUTH.getCurrentUser) ? window.YBP_AUTH.getCurrentUser().name : (YBP_DATA.user && YBP_DATA.user.name)) || 'מנהל';
  const items = loadBooklet(projectId).map(it => it.id === itemId ? {
    ...it,
    completed: true,
    completedAt: it.completedAt || new Date().toISOString(),
    completedBy: it.completedBy || who,
  } : it);
  saveBooklet(projectId, items);
}

// ────────────────────────────────────────────────────────
// BOOKLET SCREEN
// ────────────────────────────────────────────────────────
// ── Section card — רכיב מודול (אסור להגדיר בתוך רכיב אחר — גורם remount בכל הקלדה) ──
const ClientSection = ({ title, children }) => (
  <div style={{ background:'#fff', border:'1px solid #e5e7eb', borderRadius:10, padding:20, marginBottom:14 }}>
    <div style={{ fontSize:14, fontWeight:700, color:'#1a2c4a', marginBottom:14 }}>{title}</div>
    {children}
  </div>
);

// ── Client Details — קבועי קטגוריות + heuristic מ-CRM role ─────────────────
const CLIENT_DETAILS_CATEGORIES = ['יזם', 'כספים', 'שיווק', 'אדריכל', 'מכון העתקות', 'אחר'];

function roleToCat(role) {
  const r = String(role || '').toLowerCase();
  if (!r) return 'אחר';
  if (/יזם|בעלים|מנכ"ל|מנכל/.test(r)) return 'יזם';
  if (/כספ|חשב|חשבונ|הנהל"ח|הנהלח|הנהל ?ח|רו"ח|רואה/.test(r)) return 'כספים';
  if (/שיווק|marketing|מכירות/.test(r)) return 'שיווק';
  if (/אדריכל|מתכנן|architect|מעצב/.test(r)) return 'אדריכל';
  if (/העתקות|copy/.test(r)) return 'מכון העתקות';
  return 'אחר';
}

// migration מהפורמט הישן (flat) לפורמט החדש (חברה + כותרת + contacts[] + copyShop + מידע פנימי)
function migrateClientDetails(old) {
  const o = old || {};
  // אם כבר חדש — החזר עם defaults
  if (Array.isArray(o.contacts) || o.companyName !== undefined || o.copyShop) {
    return {
      companyName: o.companyName || '',
      companyId: o.companyId || '',
      companyAddress: o.companyAddress || '',
      projectTitle: o.projectTitle || '',
      projectSubtitle: o.projectSubtitle || '',
      contacts: Array.isArray(o.contacts) ? o.contacts : [],
      copyShop: o.copyShop || { name:'', contact:'', email:'', ordersPhone:'', link:'' },
      projectArea: o.projectArea || '',
      buildingFloor: o.buildingFloor || '',
      managementCompany: o.managementCompany || o.managingCompany || '',
      parking: o.parking || o.parkingSpots || '',
      paymentTerms: o.paymentTerms || '',
      advance: o.advance || o.advancePayment || '',
      vat: o.vat || '',
      notes: o.notes || '',
      driveUrl: o.driveUrl || '',
    };
  }
  // פורמט ישן (clientName, clientId, ...) → ממפים
  const contacts = [];
  if (o.clientContact || o.clientPhone || o.clientEmail) {
    contacts.push({ category:'יזם', role:'איש קשר ראשי', name:o.clientContact||'', phone:o.clientPhone||'', phone2:'', email:o.clientEmail||'' });
  }
  return {
    companyName: o.clientName || '',
    companyId: o.clientId || '',
    companyAddress: o.clientAddress || '',
    projectTitle: '',
    projectSubtitle: o.projectAddress || '',
    contacts,
    copyShop: { name:'', contact:'', email:'', ordersPhone:'', link:'' },
    projectArea: o.projectArea || '',
    buildingFloor: o.buildingFloor || '',
    managementCompany: o.managingCompany || '',
    parking: o.parkingSpots || '',
    paymentTerms: o.paymentTerms || '',
    advance: o.advancePayment || '',
    vat: o.vat || '',
    notes: [o.projectType ? 'סוג: ' + o.projectType : '', o.milestonePayments ? 'תשלומי אבני דרך: ' + o.milestonePayments : '', o.notes || ''].filter(Boolean).join('\n'),
    driveUrl: '',
  };
}

// בניית bodyHtml עבור YBPPdf — שתי עמודות לפי preview_client_pdf.html
function buildClientDetailsPdfParts(form, project) {
  const esc = (s) => String(s == null ? '' : s).replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[m]));
  const proj = project || {};
  const projTitle = (form.projectTitle || proj.name || '').trim();
  const projSub = (form.projectSubtitle || '').trim();

  // קיבוץ אנשי קשר לפי קטגוריה (לפי הסדר ב-CLIENT_DETAILS_CATEGORIES, ללא "מכון העתקות")
  const contacts = (form.contacts || []).filter(c => (c.name || '').trim() || (c.phone || '').trim() || (c.email || '').trim());
  const grouped = {};
  contacts.forEach(c => {
    const cat = c.category && CLIENT_DETAILS_CATEGORIES.includes(c.category) && c.category !== 'מכון העתקות' ? c.category : 'אחר';
    (grouped[cat] = grouped[cat] || []).push(c);
  });

  const cs = form.copyShop || {};
  const hasCopyShop = !!(cs.name || cs.contact || cs.email || cs.ordersPhone || cs.link);

  // עמודה ימין: שם פרויקט גדול + כותרת משנה + פרטי חברה
  const rightCol = [
    '<div style="width:340px;flex-shrink:0;padding:20px 24px 20px 16px;border-left:1px solid #e0e0e0;">',
      '<div style="font-size:30px;font-weight:900;color:#1a3a6b;letter-spacing:-0.5px;line-height:1.15;margin-bottom:6px;text-align:right;">' + esc(projTitle || '—') + '</div>',
      projSub ? '<div style="font-size:13px;color:#666;margin-bottom:30px;text-align:right;line-height:1.6;">' + esc(projSub).replace(/\n/g, '<br>') + '</div>' : '<div style="margin-bottom:30px;"></div>',
      '<div style="font-size:14px;font-weight:700;color:#1a3a6b;border-bottom:2px solid #1a3a6b;padding-bottom:4px;margin-bottom:14px;text-align:right;">פרטי חברה</div>',
      '<div style="font-size:13px;color:#222;line-height:1.9;text-align:right;">',
        form.companyName ? '<div style="font-weight:600;">' + esc(form.companyName) + '</div>' : '',
        form.companyId ? '<div><span style="color:#777;">ח.פ:</span> ' + esc(form.companyId) + '</div>' : '',
        form.companyAddress ? '<div><span style="color:#777;">כתובת:</span> ' + esc(form.companyAddress) + '</div>' : '',
        (!form.companyName && !form.companyId && !form.companyAddress) ? '<div style="color:#bbb;">לא הוזנו פרטי חברה</div>' : '',
      '</div>',
    '</div>',
  ].join('');

  // עמודה שמאל: אנשי קשר מקובצים + בלוק מכון העתקות
  let contactsBlocks = '';
  CLIENT_DETAILS_CATEGORIES.forEach(cat => {
    if (cat === 'מכון העתקות' || !grouped[cat]) return;
    contactsBlocks += '<div style="font-size:12px;font-weight:700;color:#1a3a6b;margin:14px 0 8px;text-align:center;border-bottom:1px solid #e0e0e0;padding-bottom:4px;letter-spacing:.5px;">' + esc(cat) + '</div>';
    grouped[cat].forEach(c => {
      const phones = [c.phone, c.phone2].filter(p => p && String(p).trim());
      contactsBlocks += [
        '<div style="text-align:center;margin-bottom:12px;padding-bottom:10px;border-bottom:1px dashed #ddd;">',
          c.name ? '<div style="font-size:14px;font-weight:700;color:#1a3a6b;margin-bottom:2px;">' + esc(c.name) + '</div>' : '',
          c.role ? '<div style="font-size:11.5px;color:#888;margin-bottom:5px;">' + esc(c.role) + '</div>' : '',
          phones.map(p => '<div style="font-size:13px;font-weight:600;color:#222;direction:ltr;unicode-bidi:embed;margin-bottom:2px;">' + esc(p) + '</div>').join(''),
          c.email ? '<div style="font-size:11px;color:#2d5ba3;direction:ltr;unicode-bidi:embed;">' + esc(c.email) + '</div>' : '',
        '</div>',
      ].join('');
    });
  });

  let copyShopHtml = '';
  if (hasCopyShop) {
    copyShopHtml = [
      '<div style="font-size:12px;font-weight:700;color:#555;margin:18px 0 10px;text-align:center;border-top:1px solid #e0e0e0;padding-top:14px;letter-spacing:.5px;">ספקים / נותני שירות</div>',
      '<div style="background:#fff9e0;border:1px solid #f0d060;border-radius:6px;padding:10px 12px;text-align:center;font-size:12px;">',
        cs.name ? '<div style="font-weight:700;color:#333;font-size:13px;margin-bottom:4px;">מכון העתקות — ' + esc(cs.name) + '</div>' : '<div style="font-weight:700;color:#333;font-size:13px;margin-bottom:4px;">מכון העתקות</div>',
        cs.contact ? '<div style="color:#666;margin-bottom:6px;">' + esc(cs.contact) + '</div>' : '',
        cs.ordersPhone ? '<div style="margin-bottom:4px;"><span style="font-size:11px;color:#777;">הזמנות: </span><span style="font-weight:600;color:#222;direction:ltr;unicode-bidi:embed;">' + esc(cs.ordersPhone) + '</span></div>' : '',
        cs.email ? '<div style="color:#2d5ba3;direction:ltr;unicode-bidi:embed;font-size:11px;margin-top:2px;">' + esc(cs.email) + '</div>' : '',
        cs.link ? '<div style="color:#2d5ba3;direction:ltr;unicode-bidi:embed;font-size:11px;margin-top:2px;">' + esc(cs.link) + '</div>' : '',
      '</div>',
    ].join('');
  }

  const leftCol = [
    '<div style="flex:1;padding:20px 18px 20px 24px;">',
      '<div style="font-size:13px;font-weight:700;color:#1a3a6b;margin-bottom:12px;text-align:center;letter-spacing:.5px;">אנשי קשר</div>',
      contactsBlocks || '<div style="text-align:center;color:#aaa;font-size:12px;padding:20px 0;">לא הוזנו אנשי קשר</div>',
      copyShopHtml,
    '</div>',
  ].join('');

  const bodyHtml = '<div style="display:flex;flex-direction:row;direction:rtl;background:#fff;border:1px solid #e5e7eb;border-radius:6px;overflow:hidden;">' + leftCol + rightCol + '</div>';

  const headerMetaHtml = '<div style="text-align:center;padding:6px 0 14px;font-size:11px;color:#888;letter-spacing:.5px;">פרטי לקוח · ' + esc(projTitle || proj.name || '') + ' · הופק ' + new Date().toLocaleDateString('he-IL') + '</div>';

  return { headerMetaHtml, bodyHtml };
}

// ── Picker למילוי מ-CRM (ybp_contacts_v1) ─────────────────────────────────
const ClientContactsPicker = ({ contacts, onConfirm, onCancel }) => {
  const [selected, setSelected] = useState({}); // { contactId: { category } }
  const [copyShopAnswer, setCopyShopAnswer] = useState('no');
  const list = (contacts || []).filter(c => c && c.active !== false).slice().sort((a,b) => (a.name||'').localeCompare(b.name||'', 'he'));

  const toggle = (c, on) => setSelected(s => {
    if (on) return { ...s, [c.id]: { category: s[c.id]?.category || roleToCat(c.role) } };
    const { [c.id]: _, ...rest } = s; return rest;
  });
  const setCat = (id, cat) => setSelected(s => ({ ...s, [id]: { ...(s[id]||{}), category: cat } }));

  const count = Object.keys(selected).length;
  const onOk = () => {
    const picked = Object.keys(selected).map(id => {
      const c = list.find(x => x.id === id);
      return c ? { contact: c, category: selected[id].category || 'אחר' } : null;
    }).filter(Boolean);
    onConfirm(picked, copyShopAnswer);
  };

  return (
    <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.5)', zIndex:9000, display:'flex', alignItems:'center', justifyContent:'center', padding:20 }}>
      <div style={{ background:'#fff', borderRadius:10, maxWidth:680, width:'100%', maxHeight:'85vh', display:'flex', flexDirection:'column', direction:'rtl' }}>
        <div style={{ padding:'14px 20px', borderBottom:'1px solid #e5e7eb', display:'flex', alignItems:'center', gap:12 }}>
          <div style={{ flex:1 }}>
            <div style={{ fontSize:16, fontWeight:700, color:'#1a2c4a' }}>מילוי מ-CRM</div>
            <div style={{ fontSize:12, color:'#6b7280' }}>נמצאו {list.length} אנשי קשר. סמן את אלה שלייבא וקבע קטגוריה לכל אחד.</div>
          </div>
          <button onClick={onCancel} style={{ background:'transparent', border:'none', cursor:'pointer', fontSize:22, color:'#9ca3af' }}>×</button>
        </div>
        <div style={{ flex:1, overflowY:'auto', padding:'8px 20px' }}>
          {list.length === 0 && <div style={{ textAlign:'center', padding:40, color:'#aaa' }}>אין אנשי קשר ב-CRM</div>}
          {list.map(c => {
            const sel = !!selected[c.id];
            return (
              <div key={c.id} style={{ display:'flex', alignItems:'center', gap:10, padding:'8px 0', borderBottom:'1px solid #f3f4f6' }}>
                <input type="checkbox" checked={sel} onChange={e=>toggle(c, e.target.checked)} style={{ width:18, height:18, cursor:'pointer', flexShrink:0 }}/>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontSize:13, fontWeight:600, color:'#1f2937' }}>{c.name || '—'}</div>
                  <div style={{ fontSize:11, color:'#6b7280', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{[c.role, c.company, c.phone, c.email].filter(Boolean).join(' · ')}</div>
                </div>
                {sel && (
                  <select value={selected[c.id]?.category || 'אחר'} onChange={e=>setCat(c.id, e.target.value)} style={{ padding:'4px 8px', border:'1px solid #e5e7eb', borderRadius:5, fontSize:12, fontFamily:'inherit' }}>
                    {CLIENT_DETAILS_CATEGORIES.filter(cat => cat !== 'מכון העתקות').map(cat => <option key={cat} value={cat}>{cat}</option>)}
                  </select>
                )}
              </div>
            );
          })}
        </div>
        <div style={{ padding:'12px 20px', borderTop:'1px solid #e5e7eb', background:'#f9fafb' }}>
          <div style={{ fontSize:12, color:'#374151', marginBottom:6 }}>מכון ההעתקות זהה לפרויקט הקודם?</div>
          <div style={{ display:'flex', gap:14, marginBottom:12 }}>
            {[['yes','כן — העתק מהפרויקט האחרון'],['no','לא / לא יודע']].map(([v,l]) => (
              <label key={v} style={{ display:'flex', alignItems:'center', gap:5, fontSize:12, cursor:'pointer' }}>
                <input type="radio" name="copyshop" value={v} checked={copyShopAnswer===v} onChange={e=>setCopyShopAnswer(e.target.value)}/>
                {l}
              </label>
            ))}
          </div>
          <div style={{ display:'flex', gap:8, justifyContent:'flex-end' }}>
            <button onClick={onCancel} style={{ padding:'8px 14px', borderRadius:6, border:'1px solid #e5e7eb', background:'#fff', fontSize:12, fontWeight:600, cursor:'pointer', fontFamily:'inherit', color:'#374151' }}>ביטול</button>
            <button onClick={onOk} disabled={count === 0} style={{ padding:'8px 14px', borderRadius:6, border:'none', background: count === 0 ? '#9ca3af' : '#1a2c4a', color:'#fff', fontSize:12, fontWeight:700, cursor:'pointer', fontFamily:'inherit' }}>מלא ({count})</button>
          </div>
        </div>
      </div>
    </div>
  );
};

// ── Add Custom Task Modal ──────────────────────────────────────────────────
const AddBookletTaskModal = ({ stages, onAdd, onClose }) => {
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');
  const [stage, setStage] = useState(stages[0]?.stage || '1');
  const [stageLabel, setStageLabel] = useState(stages[0]?.stageLabel || 'פתיחת פרויקט');
  const [required, setRequired] = useState(false);

  const inp = { width:'100%', padding:'9px 12px', border:'1px solid #e5e7eb', borderRadius:7, fontSize:13, fontFamily:'inherit', boxSizing:'border-box', direction:'rtl', outline:'none' };

  const handleAdd = () => {
    if (!title.trim()) return;
    onAdd({ title: title.trim(), description, stage, stageLabel, required });
    onClose();
  };

  return (
    <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.5)', zIndex:9999, display:'flex', alignItems:'center', justifyContent:'center', padding:16 }}
      onClick={e => e.target === e.currentTarget && onClose()}>
      <div style={{ background:'#fff', borderRadius:14, width:'100%', maxWidth:460, boxShadow:'0 20px 60px rgba(0,0,0,0.2)', fontFamily:'Assistant,sans-serif', direction:'rtl', overflow:'hidden' }}>
        {/* Header */}
        <div style={{ background:'#1a2c4a', padding:'14px 20px', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
          <span style={{ fontSize:16, fontWeight:700, color:'#fff' }}>הוספת משימה לחוברת</span>
          <button onClick={onClose} style={{ background:'none', border:'none', color:'rgba(255,255,255,0.7)', fontSize:20, cursor:'pointer', lineHeight:1 }}>✕</button>
        </div>
        {/* Body */}
        <div style={{ padding:20, display:'flex', flexDirection:'column', gap:14 }}>
          <div>
            <label style={{ fontSize:11, fontWeight:700, color:'#374151', display:'block', marginBottom:5, textTransform:'uppercase', letterSpacing:0.3 }}>כותרת המשימה *</label>
            <input value={title} onChange={e => setTitle(e.target.value)} autoFocus
              placeholder="לדוגמה: קבלת אישור עירייה..." style={inp}/>
          </div>
          <div>
            <label style={{ fontSize:11, fontWeight:700, color:'#374151', display:'block', marginBottom:5, textTransform:'uppercase', letterSpacing:0.3 }}>תיאור (אופציונלי)</label>
            <textarea value={description} onChange={e => setDescription(e.target.value)}
              placeholder="פרטים נוספים על המשימה..."
              rows={2} style={{ ...inp, resize:'vertical' }}/>
          </div>
          <div>
            <label style={{ fontSize:11, fontWeight:700, color:'#374151', display:'block', marginBottom:5, textTransform:'uppercase', letterSpacing:0.3 }}>שלב בחוברת</label>
            <select value={stage} onChange={e => {
              const s = stages.find(x => x.stage === e.target.value);
              setStage(e.target.value);
              setStageLabel(s?.stageLabel || '');
            }} style={{ ...inp, cursor:'pointer' }}>
              {stages.map(s => (
                <option key={s.stage} value={s.stage}>{s.stage} — {s.stageLabel}</option>
              ))}
            </select>
          </div>
          <label style={{ display:'flex', alignItems:'center', gap:10, cursor:'pointer', fontSize:13 }}>
            <input type="checkbox" checked={required} onChange={e => setRequired(e.target.checked)}
              style={{ width:16, height:16, cursor:'pointer' }}/>
            <span style={{ fontWeight:600, color:'#374151' }}>משימת חובה</span>
            <span style={{ fontSize:11, color:'#9ca3af' }}>(יסומן באדום)</span>
          </label>
        </div>
        {/* Footer */}
        <div style={{ padding:'12px 20px', borderTop:'1px solid #f3f4f6', display:'flex', gap:8, justifyContent:'flex-end' }}>
          <button onClick={onClose} style={{ padding:'8px 16px', borderRadius:7, border:'1px solid #e5e7eb', background:'#fff', color:'#374151', fontSize:13, cursor:'pointer', fontFamily:'inherit' }}>
            ביטול
          </button>
          <button onClick={handleAdd} disabled={!title.trim()} style={{
            padding:'8px 18px', borderRadius:7, border:'none',
            background: title.trim() ? '#1a2c4a' : '#e5e7eb',
            color: title.trim() ? '#fff' : '#9ca3af',
            fontSize:13, fontWeight:700, cursor: title.trim() ? 'pointer' : 'not-allowed', fontFamily:'inherit',
          }}>
            + הוסף משימה
          </button>
        </div>
      </div>
    </div>
  );
};

// ── StageSection — collapsible stage with status badge ──────────────────────
const STAGE_STATUS_LABEL = { pending: 'לא התחיל', active: 'בביצוע', done: 'הושלם', empty: '' };
const STAGE_STATUS_COLOR = { pending: '#9ca3af', active: '#f59e0b', done: '#10b981', empty: '#9ca3af' };
const STAGE_STATUS_BG    = { pending: '#f3f4f6', active: '#fffbeb', done: '#ecfdf5', empty: '#f3f4f6' };

const StageSection = ({ stage, items, onOpenGantt, onOpenForm, onToggleItem }) => {
  const stageItems = items.filter(it => it.stage === stage.id);
  const completable = stageItems.filter(it => it.type !== 'gantt');
  const done = completable.filter(it => it.completed).length;
  const status = completable.length === 0 ? 'empty'
    : done === 0 ? 'pending'
    : done === completable.length ? 'done'
    : 'active';
  const [open, setOpen] = React.useState(status !== 'done');

  return (
    <div style={{ marginBottom: 16 }}>
      {/* Stage header */}
      <div onClick={() => setOpen(o => !o)}
        style={{ display:'flex', alignItems:'center', gap:10, padding:'12px 16px',
          background: STAGE_STATUS_BG[status], border:'1px solid #e5e7eb',
          borderRadius: open ? '10px 10px 0 0' : 10, cursor:'pointer', userSelect:'none' }}>
        <span style={{ fontSize:18 }}>{stage.icon}</span>
        <span style={{ flex:1, fontWeight:700, fontSize:14, color:'#1a2c4a' }}>{stage.label}</span>
        <span style={{ fontSize:11, fontWeight:700, color: STAGE_STATUS_COLOR[status],
          background:'#fff', border:`1px solid ${STAGE_STATUS_COLOR[status]}`,
          borderRadius:20, padding:'2px 10px' }}>
          {STAGE_STATUS_LABEL[status]}
        </span>
        <span style={{ fontSize:12, color:'#9ca3af' }}>{done}/{completable.length}</span>
        <span style={{ fontSize:14, color:'#9ca3af' }}>{open ? '▲' : '▼'}</span>
      </div>

      {/* Stage items */}
      {open && (
        <div style={{ border:'1px solid #e5e7eb', borderTop:'none', borderRadius:'0 0 10px 10px', overflow:'hidden' }}>
          {stageItems.map((item, idx) => {
            // Gantt card
            if (item.type === 'gantt') return (
              <div key={item.id}
                style={{ padding:'16px 20px', background:'#eff6ff',
                  borderTop: idx > 0 ? '1px solid #e5e7eb' : 'none',
                  display:'flex', alignItems:'center', gap:14 }}>
                <span style={{ fontSize:22 }}>📅</span>
                <div style={{ flex:1 }}>
                  <div style={{ fontWeight:700, fontSize:14, color:'#1e3a8a' }}>{item.title}</div>
                  <div style={{ fontSize:12, color:'#3b82f6' }}>{item.description}</div>
                </div>
                <button onClick={() => onOpenGantt && onOpenGantt()}
                  style={{ padding:'9px 18px', background:'#1d4ed8', color:'#fff', border:'none',
                    borderRadius:8, fontWeight:700, fontSize:13, cursor:'pointer',
                    fontFamily:'inherit', whiteSpace:'nowrap' }}>
                  פתח גאנט ביצוע ←
                </button>
              </div>
            );

            // Regular item
            return (
              <div key={item.id}
                style={{ padding:'14px 20px', background: item.completed ? '#f0fdf4' : '#fff',
                  borderTop: idx > 0 ? '1px solid #f3f4f6' : 'none',
                  display:'flex', alignItems:'flex-start', gap:12 }}>
                <button onClick={() => onToggleItem(item.id)}
                  style={{ flexShrink:0, marginTop:2, width:22, height:22, borderRadius:6,
                    border: item.completed ? 'none' : '2px solid #d1d5db',
                    background: item.completed ? '#10b981' : '#fff',
                    cursor:'pointer', display:'flex', alignItems:'center',
                    justifyContent:'center', color:'#fff', fontSize:13, fontWeight:700 }}>
                  {item.completed ? '✓' : ''}
                </button>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ display:'flex', alignItems:'center', gap:8, flexWrap:'wrap' }}>
                    <span style={{ fontWeight:600, fontSize:13,
                      color: item.completed ? '#6b7280' : '#111827',
                      textDecoration: item.completed ? 'line-through' : 'none' }}>
                      {item.title}
                    </span>
                    {item.required && !item.completed && (
                      <span style={{ fontSize:10, background:'#fef3c7', color:'#92400e',
                        border:'1px solid #fcd34d', borderRadius:10, padding:'1px 7px', fontWeight:700 }}>
                        חובה
                      </span>
                    )}
                    {item.type === 'form' && !item.completed && (
                      <button onClick={() => onOpenForm && onOpenForm(item.formScreen)}
                        style={{ fontSize:11, color:'#2563eb', background:'#eff6ff',
                          border:'1px solid #bfdbfe', borderRadius:6, padding:'2px 8px',
                          cursor:'pointer', fontFamily:'inherit', fontWeight:600 }}>
                        פתח טופס
                      </button>
                    )}
                  </div>
                  <div style={{ fontSize:12, color:'#6b7280', marginTop:2 }}>{item.description}</div>
                  {item.defaultDue && !item.completed && (
                    <div style={{ fontSize:11, color:'#9ca3af', marginTop:3 }}>
                      🗓 יעד: {new Date(item.defaultDue).toLocaleDateString('he-IL')}
                    </div>
                  )}
                  {item.completed && item.completedAt && (
                    <div style={{ fontSize:11, color:'#10b981', marginTop:3 }}>
                      ✓ הושלם {new Date(item.completedAt).toLocaleDateString('he-IL')}
                      {item.completedBy ? ` · ${item.completedBy}` : ''}
                    </div>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};

const BookletScreen = ({ projectId, onBack, onOpenForm, onOpenGantt }) => {
  const project = YBP_DATA.projects.find(p => p.id === projectId);
  const [items, setItems] = useState(() => loadBooklet(projectId));
  const [expandedItem, setExpandedItem] = useState(null);
  const [notesDraft, setNotesDraft] = useState({});
  const [showAddModal, setShowAddModal] = useState(false);
  const [deleteConfirm, setDeleteConfirm] = useState(null); // id של פריט למחיקה

  const STAGES = [
    { id: '1', label: 'פתיחת פרויקט', icon: '🚀' },
    { id: '2', label: 'תכנון',         icon: '📐' },
    { id: '3', label: 'קבלנים וספקים', icon: '🤝' },
    { id: '4', label: 'ביצוע בשטח',   icon: '🏗️' },
    { id: '5', label: 'סיום ומסירה',   icon: '🏁' },
  ];

  const handleToggleItem = (itemId) => {
    const updated = items.map(it => it.id === itemId
      ? { ...it,
          completed:   !it.completed,
          completedAt: !it.completed ? new Date().toISOString() : null,
          completedBy: !it.completed ? (window.YBP_AUTH?.getCurrentUser?.()?.name || 'מנהל') : null }
      : it);
    setItems(updated);
    saveBooklet(projectId, updated);
  };

  // הוספת משימה מותאמת אישית
  const addCustomTask = ({ title, description, stage, stageLabel, required }) => {
    const newItem = {
      id: 'custom_' + Date.now(),
      stage, stageLabel, title, description,
      type: 'checklist',
      required,
      order: items.length + 1,
      completed: false, completedAt: null, completedBy: null, notes: '',
      isCustom: true,
    };
    const updated = [...items, newItem];
    setItems(updated);
    saveBooklet(projectId, updated);
    if (window.toastSuccess) window.toastSuccess('משימה נוספה לחוברת');
  };

  // מחיקת משימה (רק משימות custom)
  const deleteTask = (id) => {
    const updated = items.filter(item => item.id !== id);
    setItems(updated);
    saveBooklet(projectId, updated);
    setDeleteConfirm(null);
    if (window.toastSuccess) window.toastSuccess('משימה נמחקה');
  };

  const toggleComplete = (id) => {
    const updated = items.map(item => item.id === id ? {
      ...item,
      completed: !item.completed,
      completedAt: !item.completed ? new Date().toISOString() : null,
      completedBy: !item.completed ? ((window.YBP_AUTH && window.YBP_AUTH.getCurrentUser) ? window.YBP_AUTH.getCurrentUser().name : YBP_DATA.user?.name) || 'מנהל' : null,
    } : item);
    setItems(updated);
    saveBooklet(projectId, updated);
  };

  const saveNotes = (id) => {
    const updated = items.map(item => item.id === id ? { ...item, notes: notesDraft[id] || '' } : item);
    setItems(updated);
    saveBooklet(projectId, updated);
  };

  // Group by stage
  const stages = [...new Set(items.map(i => i.stage))].map(s => ({
    stage: s,
    stageLabel: items.find(i => i.stage === s)?.stageLabel || s,
  }));
  const completedCount = items.filter(i => i.completed).length;
  const requiredCount = items.filter(i => i.required).length;
  const completedRequired = items.filter(i => i.required && i.completed).length;
  const progress = Math.round(completedCount / items.length * 100);

  const stageColors = { '1':'#1a2c4a','2':'#1d4ed8','3':'#7c3aed','4':'#dc2626','5':'#10b981' };
  const typeIcons = { form:'📋', report:'📊', document:'📄', checklist:'✅' };

  return (
    <div style={{ minHeight:'100%', background:'#f6f7f9', fontFamily:'Assistant, sans-serif', direction:'rtl', paddingBottom:40 }}>
      {/* Modals */}
      {showAddModal && (
        <AddBookletTaskModal
          stages={stages}
          onAdd={addCustomTask}
          onClose={() => setShowAddModal(false)}
        />
      )}
      {deleteConfirm && (
        <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.5)', zIndex:9999, display:'flex', alignItems:'center', justifyContent:'center', padding:16 }}>
          <div style={{ background:'#fff', borderRadius:12, padding:24, maxWidth:340, width:'100%', textAlign:'center', fontFamily:'Assistant,sans-serif', direction:'rtl' }}>
            <div style={{ fontSize:32, marginBottom:12 }}>🗑️</div>
            <div style={{ fontSize:16, fontWeight:700, color:'#1a2c4a', marginBottom:8 }}>מחיקת משימה</div>
            <div style={{ fontSize:13, color:'#6b7280', marginBottom:20 }}>
              האם למחוק את "<b>{items.find(i=>i.id===deleteConfirm)?.title}</b>"?<br/>פעולה זו אינה ניתנת לביטול.
            </div>
            <div style={{ display:'flex', gap:10, justifyContent:'center' }}>
              <button onClick={() => setDeleteConfirm(null)} style={{ padding:'9px 20px', borderRadius:7, border:'1px solid #e5e7eb', background:'#fff', color:'#374151', fontSize:13, cursor:'pointer', fontFamily:'inherit' }}>ביטול</button>
              <button onClick={() => deleteTask(deleteConfirm)} style={{ padding:'9px 20px', borderRadius:7, border:'none', background:'#dc2626', color:'#fff', fontSize:13, fontWeight:700, cursor:'pointer', fontFamily:'inherit' }}>מחק</button>
            </div>
          </div>
        </div>
      )}

      {/* Header */}
      <header style={{
        background: 'var(--ybp-panel, #fff)', color: 'var(--ybp-ink, #111827)',
        padding: '0 16px', height: 52,
        display: 'flex', alignItems: 'center', gap: 12, position: 'sticky', top: 0, zIndex: 10,
        borderBottom: '1px solid var(--ybp-border, #e5e7eb)',
      }}>
        <button onClick={onBack} style={{ background: 'transparent', border: 'none', color: 'var(--ybp-ink-soft, #6b7280)', cursor: 'pointer', padding: 6 }}>
          <Icon name="chevronR" size={16}/>
        </button>
        <img src="assets/ybp-logo-new.png" alt="YBP" style={{ height: 26, objectFit: 'contain' }}/>
        <div style={{ width: 1, height: 30, background: 'var(--ybp-border, #e5e7eb)' }}/>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 11, color: 'var(--ybp-ink-faint, #9ca3af)' }}>{project?.name}</div>
          <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--ybp-ink, #111827)' }}>חוברת פרויקט</div>
        </div>
        <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ybp-ink-soft, #6b7280)' }}>
          {completedCount}/{items.length} הושלמו
        </div>
        <button onClick={() => setShowAddModal(true)} style={{
          background: 'var(--ybp-navy, #1a2c4a)', border: 'none',
          color: '#fff', padding: '6px 14px', borderRadius: 7, fontSize: 12, fontWeight: 700,
          cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 5,
        }}>
          + משימה
        </button>
      </header>

      <div style={{ maxWidth:860, margin:'0 auto', padding:'20px 16px' }}>
        {/* Progress bar */}
        <div style={{ background:'#fff', border:'1px solid #e5e7eb', borderRadius:10, padding:'16px 20px', marginBottom:20 }}>
          <div style={{ display:'flex', justifyContent:'space-between', marginBottom:8, fontSize:13 }}>
            <span style={{ fontWeight:700, color:'#1a2c4a' }}>התקדמות כוללת</span>
            <span style={{ color:'#6b7280' }}>{completedRequired}/{requiredCount} חובה הושלמו</span>
          </div>
          <div style={{ height:10, background:'#f1f5f9', borderRadius:5, overflow:'hidden' }}>
            <div style={{ height:'100%', width:`${progress}%`, background:'#1a2c4a', borderRadius:5, transition:'width 0.4s' }}/>
          </div>
          <div style={{ display:'flex', justifyContent:'space-between', marginTop:6, fontSize:11, color:'#9ca3af' }}>
            <span>{progress}% הושלם</span>
            <span>{items.length - completedCount} פריטים ממתינים</span>
          </div>
        </div>

        {/* Stages */}
        {STAGES.map(stage => (
          <StageSection
            key={stage.id}
            stage={stage}
            items={items}
            onOpenGantt={onOpenGantt}
            onOpenForm={onOpenForm}
            onToggleItem={handleToggleItem}
          />
        ))}

        {/* Footer */}
        <div style={{ textAlign:'center', fontSize:11, color:'#9ca3af', marginTop:20 }}>
          © 2026 YBPROJECTS · כל הזכויות שמורות
        </div>
      </div>
    </div>
  );
};

// ────────────────────────────────────────────────────────
// CLIENT DETAILS FORM — דף פרטי לקוח
// ────────────────────────────────────────────────────────
const ClientDetailsForm = ({ projectId, bookletItem, onBack, onComplete, onOpenContacts }) => {
  const project = YBP_DATA.projects.find(p => p.id === projectId);
  const STORAGE_KEY = `ybp_client_details_${projectId}`;

  const [form, setForm] = useState(() => {
    try { return migrateClientDetails(JSON.parse(localStorage.getItem(STORAGE_KEY)) || {}); }
    catch(e) { return migrateClientDetails({}); }
  });
  const [showPicker, setShowPicker] = useState(false);
  const [savedAt, setSavedAt] = useState(null);
  const [driveUrl, setDriveUrl] = useState(form.driveUrl || '');
  const [busy, setBusy] = useState(false);
  const [crmCount, setCrmCount] = useState(() => {
    try { return (JSON.parse(localStorage.getItem('ybp_contacts_v1') || '[]') || []).length; }
    catch { return 0; }
  });

  const upd = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const updContact = (i, k, v) => setForm(f => ({
    ...f,
    contacts: (f.contacts || []).map((c, idx) => idx === i ? { ...c, [k]: v } : c),
  }));
  const addContact = () => setForm(f => ({
    ...f,
    contacts: [...(f.contacts || []), { category:'אחר', role:'', name:'', phone:'', phone2:'', email:'' }],
  }));
  const removeContact = (i) => setForm(f => ({
    ...f,
    contacts: (f.contacts || []).filter((_, idx) => idx !== i),
  }));
  const updCopyShop = (k, v) => setForm(f => ({ ...f, copyShop: { ...(f.copyShop || {}), [k]: v } }));

  const persist = (extra = {}) => {
    const data = { ...form, driveUrl, ...extra };
    localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
    setSavedAt(new Date().toISOString());
    return data;
  };

  // ── PDF / share / Drive handlers ──────────────────────────────────────────
  const getLogoSrc = () => document.querySelector('img[alt="YBP"]')?.src || '';
  const fileName = () => `פרטי לקוח - ${form.projectTitle || project?.name || projectId}`;

  const handlePreviewPdf = () => {
    persist();
    const { headerMetaHtml, bodyHtml } = buildClientDetailsPdfParts(form, project);
    window.YBPPdf.generatePdf({ orientation:'portrait', logoSrc:getLogoSrc(), fileName:fileName(), headerMetaHtml, bodyHtml, sigHtml:'', projectId, uploadToDrive:false });
  };

  const handlePrint = () => {
    persist();
    const { headerMetaHtml, bodyHtml } = buildClientDetailsPdfParts(form, project);
    window.YBPPdf.openPrintWindow({ orientation:'portrait', logoSrc:getLogoSrc(), fileName:fileName(), headerMetaHtml, bodyHtml, sigHtml:'' });
  };

  const handleSaveToDrive = async (silent = false) => {
    if (!project?.driveFolderId) {
      if (!silent) alert('לפרויקט אין תיקיית Drive מוגדרת — ניתן לשמור מקומית בלבד');
      return null;
    }
    persist();
    setBusy(true);
    try {
      const settings = (() => { try { return JSON.parse(localStorage.getItem('ybp_settings') || '{}'); } catch { return {}; } })();
      const webhookUrl = settings.webhooks?.PLACEHOLDER_UPLOAD_REPORT_PDF || 'https://hook.eu2.make.com/cwhco2m6u2m48ey692n7n7wagoz8cg0i';
      const sk = settings.webhooks?._securityKey || '1h4M4SEXbhoYF1YVW1mS6YJZs84yxSVHaBjPDDxMpbak';
      const { headerMetaHtml, bodyHtml } = buildClientDetailsPdfParts(form, project);
      const date = new Date().toISOString().slice(0,10);
      const resp = await fetch(webhookUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          _sk: sk,
          manager: ((window.YBP_AUTH && window.YBP_AUTH.getCurrentUser) ? window.YBP_AUTH.getCurrentUser().name : YBP_DATA.user?.name) || 'מנהל',
          project: project?.name || '',
          project_id: projectId,
          drive_folder_id: project?.driveFolderId || '',
          subfolder_path: 'מסמכים/פרטי לקוח',
          type_name: 'דף פרטי לקוח',
          date,
          report_id: `client-details-${projectId}`,
          format: 'html',
          html: headerMetaHtml + bodyHtml,
        }),
      });
      if (!resp.ok) {
        if (!silent) alert('שגיאה בשליחה ל-Drive — בדוק webhook');
        return null;
      }
      const data = await resp.json().catch(() => ({}));
      const url = data.file_url || data.driveUrl || '';
      if (url) {
        setDriveUrl(url);
        persist({ driveUrl: url });
      }
      if (!silent) alert('✓ הקובץ הועלה ל-Drive!\n📁 ' + (url || project?.name || ''));
      return url;
    } catch (e) {
      if (!silent) alert('⚠️ שגיאת חיבור ל-Drive');
      return null;
    } finally {
      setBusy(false);
    }
  };

  const getDist = () => { try { return JSON.parse(localStorage.getItem(`ybp_dist_${projectId}`) || '{}'); } catch { return {}; } };

  const handleShareWA = () => {
    if (!driveUrl) { alert('יש להעלות ל-Drive קודם — לחץ "שמור ב-Drive" או "אשר וסמן כהושלם"'); return; }
    const dist = getDist();
    const wa = (dist.waPhone || '').replace(/[^0-9+]/g, '');
    const text = encodeURIComponent(`פרטי לקוח - ${form.projectTitle || project?.name || ''}\n${driveUrl}`);
    window.open(wa ? `https://wa.me/${wa}?text=${text}` : `https://web.whatsapp.com/send?text=${text}`, '_blank');
  };

  const handleShareGmail = () => {
    if (!driveUrl) { alert('יש להעלות ל-Drive קודם — לחץ "שמור ב-Drive" או "אשר וסמן כהושלם"'); return; }
    const dist = getDist();
    const to = (dist.emails || []).join(',');
    const su = encodeURIComponent(`פרטי לקוח - ${form.projectTitle || project?.name || ''}`);
    const body = encodeURIComponent(driveUrl);
    window.open(`https://mail.google.com/mail/?view=cm&to=${to}&su=${su}&body=${body}`, '_blank');
  };

  const handleShareAll = async () => {
    let url = driveUrl;
    if (!url) url = await handleSaveToDrive(false);
    if (!url) return;
    handleShareWA();
    setTimeout(() => handleShareGmail(), 400);
  };

  const save = async (markDone = false) => {
    persist();
    if (markDone) {
      const url = await handleSaveToDrive(false);
      // גם אם ה-Drive נכשל — סמן כהושלם (PDF נשמר מקומית, נתן יכול לנסות שוב)
      markBookletItemComplete(projectId, 'client-details');
      onComplete?.();
      void url;
    } else {
      onBack?.();
    }
  };

  // ── Picker confirm: merge picked contacts + optional copyShop carryover ─
  const onPickerConfirm = (picked, copyShopAnswer) => {
    const newRows = picked.map(p => ({
      category: p.category || 'אחר',
      role:  p.contact.role  || '',
      name:  p.contact.name  || '',
      phone: p.contact.phone || '',
      phone2: '',
      email: p.contact.email || '',
    }));
    let copyShop = form.copyShop || {};
    if (copyShopAnswer === 'yes' && !((copyShop.name || '').trim())) {
      try {
        const keys = Object.keys(localStorage).filter(k => k.startsWith('ybp_client_details_') && k !== STORAGE_KEY);
        // עדיפות לרשומה אחרונה שיש לה copyShop.name
        for (const k of keys.reverse()) {
          const d = JSON.parse(localStorage.getItem(k));
          if (d && d.copyShop && (d.copyShop.name || '').trim()) { copyShop = d.copyShop; break; }
        }
      } catch {}
    }
    setForm(f => ({
      ...f,
      contacts: [...(f.contacts || []), ...newRows],
      copyShop,
    }));
    setShowPicker(false);
  };

  const inp = { width:'100%', padding:'8px 10px', border:'1px solid #e5e7eb', borderRadius:6, fontSize:13, fontFamily:'inherit', background:'#fff', boxSizing:'border-box', direction:'rtl' };
  const lbl = { fontSize:11, fontWeight:600, color:'#6b7280', display:'block', marginBottom:4 };

  const toolbarBtn = (b) => ({
    background: b.bg || '#fff', color: b.color || '#374151',
    border: `1px solid ${b.bg ? b.bg : '#e5e7eb'}`,
    borderRadius:6, padding:'6px 12px', fontSize:12, fontWeight:600, fontFamily:'inherit',
    cursor: busy ? 'not-allowed' : 'pointer', display:'flex', alignItems:'center', gap:5,
    opacity: busy ? 0.55 : 1, whiteSpace:'nowrap',
  });

  return (
    <div style={{ minHeight:'100%', background:'#f6f7f9', fontFamily:'Assistant, sans-serif', direction:'rtl', paddingBottom:88 }}>
      <header style={{ background:'#1a2c4a', color:'#fff', padding:'0 16px', height:52, display:'flex', alignItems:'center', gap:12, position:'sticky', top:0, zIndex:10 }}>
        <button onClick={onBack} style={{ background:'transparent', border:'none', color:'#9ca3af', cursor:'pointer', padding:6 }}>
          <Icon name="chevronR" size={16}/>
        </button>
        <div style={{ flex:1, minWidth:0 }}>
          <div style={{ fontSize:11, opacity:0.7, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{project?.name}</div>
          <div style={{ fontSize:14, fontWeight:700 }}>דף פרטי לקוח</div>
        </div>
        {savedAt && <div style={{ fontSize:11, opacity:0.6 }}>✓ נשמר {new Date(savedAt).toLocaleTimeString('he-IL', {hour:'2-digit',minute:'2-digit'})}</div>}
      </header>

      {/* Toolbar */}
      <div style={{ background:'#fff', borderBottom:'1px solid #e5e7eb', padding:'8px 16px', display:'flex', gap:6, flexWrap:'wrap', overflowX:'auto' }}>
        {[
          { label:'תצוגת PDF',    icon:'👁️', onClick: handlePreviewPdf },
          { label:'הדפס',         icon:'🖨️', onClick: handlePrint },
          { label:'שמור ב-Drive', icon:'☁️', onClick: () => handleSaveToDrive(false), color:'#4338ca' },
          { label:'WhatsApp',     icon:'💬', onClick: handleShareWA,    color:'#16a34a' },
          { label:'Gmail',        icon:'✉️', onClick: handleShareGmail, color:'#dc2626' },
          { label:'שלח הכל',      icon:'🚀', onClick: handleShareAll,   color:'#fff', bg:'#1a2c4a' },
        ].map(b => (
          <button key={b.label} onClick={b.onClick} disabled={busy} style={toolbarBtn(b)}>
            <span>{b.icon}</span> {b.label}
          </button>
        ))}
      </div>

      <div style={{ maxWidth:780, margin:'0 auto', padding:'18px 16px' }}>
        {driveUrl && (
          <div style={{ background:'#dcfce7', border:'1px solid #86efac', borderRadius:6, padding:10, fontSize:12, color:'#065f46', textAlign:'center', marginBottom:14 }}>
            ✓ ה-PDF הועלה ל-Drive: <a href={driveUrl} target="_blank" rel="noreferrer" style={{ color:'#047857', textDecoration:'underline' }}>פתח ב-Drive</a>
          </div>
        )}

        {/* 1. פרטי החברה */}
        <ClientSection title="פרטי החברה">
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
            {[['companyName','שם החברה'],['companyId','ח.פ / ת.ז'],['companyAddress','כתובת החברה']].map(([k,l]) => (
              <div key={k} style={k==='companyAddress'?{gridColumn:'1 / -1'}:null}>
                <label style={lbl}>{l}</label>
                <input value={form[k]||''} onChange={e=>upd(k,e.target.value)} style={inp}/>
              </div>
            ))}
          </div>
        </ClientSection>

        {/* 2. כותרת הפרויקט ב-PDF */}
        <ClientSection title="כותרת הפרויקט ב-PDF">
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
            <div>
              <label style={lbl}>שם הפרויקט</label>
              <input value={form.projectTitle || ''} onChange={e=>upd('projectTitle',e.target.value)} placeholder={project?.name || ''} style={inp}/>
            </div>
            <div>
              <label style={lbl}>כותרת משנה / מיקום מדויק</label>
              <input value={form.projectSubtitle || ''} onChange={e=>upd('projectSubtitle',e.target.value)} placeholder='למשל: טרמינל 3 (אחרי ביקורת דרכונים)' style={inp}/>
            </div>
          </div>
        </ClientSection>

        {/* 3. אנשי קשר (דינמי) */}
        <ClientSection title={
          <div style={{ display:'flex', alignItems:'center', gap:10 }}>
            <span>אנשי קשר</span>
            {crmCount > 0 && (
              <button onClick={() => setShowPicker(true)} style={{ marginRight:'auto', background:'#eef2ff', color:'#4338ca', border:'1px solid #c7d2fe', borderRadius:6, padding:'4px 10px', fontSize:11, fontWeight:600, cursor:'pointer', fontFamily:'inherit' }}>
                ⬇ מלא מאנשי קשר ({crmCount})
              </button>
            )}
          </div>
        }>
          {(form.contacts || []).length === 0 && (
            <div style={{ padding:'14px 0', textAlign:'center', color:'#9ca3af', fontSize:12 }}>אין עדיין אנשי קשר. לחץ "+ הוסף איש קשר" להתחיל.</div>
          )}
          {(form.contacts || []).map((c, i) => (
            <div key={i} style={{ display:'grid', gridTemplateColumns:'110px 1.2fr 1.2fr 0.95fr 0.95fr 1.3fr 28px', gap:6, marginBottom:8, alignItems:'end' }}>
              <div>
                <label style={lbl}>קטגוריה</label>
                <select value={c.category || 'אחר'} onChange={e=>updContact(i,'category',e.target.value)} style={inp}>
                  {CLIENT_DETAILS_CATEGORIES.filter(cat => cat !== 'מכון העתקות').map(cat => <option key={cat} value={cat}>{cat}</option>)}
                </select>
              </div>
              <div><label style={lbl}>תפקיד</label><input value={c.role||''} onChange={e=>updContact(i,'role',e.target.value)} style={inp} placeholder='סמנכ"ל כספים'/></div>
              <div><label style={lbl}>שם</label><input value={c.name||''} onChange={e=>updContact(i,'name',e.target.value)} style={inp}/></div>
              <div><label style={lbl}>טלפון</label><input value={c.phone||''} onChange={e=>updContact(i,'phone',e.target.value)} style={{...inp, direction:'ltr', textAlign:'right'}}/></div>
              <div><label style={lbl}>טל' נוסף</label><input value={c.phone2||''} onChange={e=>updContact(i,'phone2',e.target.value)} style={{...inp, direction:'ltr', textAlign:'right'}}/></div>
              <div><label style={lbl}>מייל</label><input value={c.email||''} onChange={e=>updContact(i,'email',e.target.value)} style={{...inp, direction:'ltr', textAlign:'right'}}/></div>
              <button onClick={() => removeContact(i)} title="מחק שורה" style={{ background:'transparent', border:'none', cursor:'pointer', color:'#dc2626', fontSize:16, padding:'6px 0', alignSelf:'center' }}>🗑️</button>
            </div>
          ))}
          <button onClick={addContact} style={{ background:'#fff', color:'#1a2c4a', border:'1px dashed #1a2c4a', borderRadius:6, padding:'8px 14px', fontSize:12, fontWeight:600, cursor:'pointer', fontFamily:'inherit', marginTop:8 }}>
            + הוסף איש קשר
          </button>
          {onOpenContacts && (
            <div style={{ marginTop:12, textAlign:'left' }}>
              <button onClick={onOpenContacts} style={{ background:'transparent', border:'none', color:'#4338ca', fontSize:11, cursor:'pointer', fontFamily:'inherit', textDecoration:'underline' }}>← עבור ל-CRM</button>
            </div>
          )}
        </ClientSection>

        {/* 4. מכון העתקות */}
        <ClientSection title="מכון העתקות">
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
            {[['name','שם המכון'],['contact','איש קשר'],['email','מייל'],['ordersPhone','טלפון הזמנות'],['link','קישור / אתר']].map(([k,l]) => (
              <div key={k} style={k==='link'?{gridColumn:'1 / -1'}:null}>
                <label style={lbl}>{l}</label>
                <input value={(form.copyShop && form.copyShop[k]) || ''} onChange={e=>updCopyShop(k, e.target.value)} style={k==='email'||k==='link'||k==='ordersPhone'?{...inp, direction:'ltr', textAlign:'right'}:inp}/>
              </div>
            ))}
          </div>
        </ClientSection>

        {/* 5. מידע פנימי */}
        <ClientSection title="מידע פנימי (לא מופיע ב-PDF)">
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
            {[
              ['projectArea','שטח (מ"ר)'],
              ['buildingFloor','קומה / מיקום בבניין'],
              ['managementCompany','חברת ניהול'],
              ['parking','חניות'],
              ['paymentTerms','תנאי תשלום'],
              ['advance','מקדמה'],
              ['vat','מע"מ'],
            ].map(([k,l]) => (
              <div key={k}>
                <label style={lbl}>{l}</label>
                <input value={form[k]||''} onChange={e=>upd(k,e.target.value)} style={inp}/>
              </div>
            ))}
          </div>
          <div style={{ marginTop:12 }}>
            <label style={lbl}>הערות</label>
            <textarea value={form.notes||''} onChange={e=>upd('notes',e.target.value)} rows={3} style={{ ...inp, resize:'vertical' }}/>
          </div>
        </ClientSection>
      </div>

      {/* Sticky bottom */}
      <div style={{ position:'fixed', bottom:0, insetInline:0, background:'#1a2c4a', padding:'12px 20px', display:'flex', gap:10, justifyContent:'flex-end', zIndex:20 }}>
        <button onClick={() => save(false)} disabled={busy} style={{ padding:'9px 18px', borderRadius:6, border:'1px solid rgba(255,255,255,0.3)', background:'transparent', color:'#fff', fontSize:13, cursor:busy?'not-allowed':'pointer', fontFamily:'inherit', opacity:busy?0.55:1 }}>
          שמור טיוטה
        </button>
        <button onClick={() => save(true)} disabled={busy} style={{ padding:'9px 18px', borderRadius:6, border:'none', background:'#10b981', color:'#fff', fontSize:13, fontWeight:700, cursor:busy?'not-allowed':'pointer', fontFamily:'inherit', opacity:busy?0.55:1 }}>
          {busy ? '⏳ מעלה ל-Drive...' : '✓ אשר וסמן כהושלם'}
        </button>
      </div>

      {showPicker && (
        <ClientContactsPicker
          contacts={(() => { try { return JSON.parse(localStorage.getItem('ybp_contacts_v1') || '[]'); } catch { return []; } })()}
          onCancel={() => setShowPicker(false)}
          onConfirm={onPickerConfirm}
        />
      )}
    </div>
  );
};

// ────────────────────────────────────────────────────────
// INFRA SURVEY — דוח סקר תשתיות (מבוסס על קובץ אקסל)
// ────────────────────────────────────────────────────────
const InfraSurveyForm = ({ projectId, onBack, onComplete }) => {
  const project = YBP_DATA.projects.find(p => p.id === projectId);
  const STORAGE_KEY = `ybp_infra_survey_${projectId}`;

  // Full survey structure based on the Excel file
  const SECTIONS = [
    {
      id: 'envelope', label: 'מעטפת', en: 'ASSET CONDITION', color: '#374151',
      items: [
        { id: 'walls', label: 'קירות', en: 'WALLS' },
        { id: 'floor', label: 'רצפה', en: 'FLOOR' },
        { id: 'ceiling', label: 'גובה מילוי', en: 'CEILING' },
        { id: 'exits', label: 'פתחים קיימים', en: 'EXISTING EXITS' },
      ]
    },
    {
      id: 'water', label: 'מערכות אינסטלציה', en: 'WATER & SEWAGE', color: '#0891b2',
      items: [
        { id: 'water_feed', label: 'הזנת מים', en: 'WATER FEED' },
        { id: 'water_meter', label: 'שעון מים', en: 'WATER METER' },
        { id: 'drains', label: 'ניקוזים', en: 'EXISTING DRAINS' },
        { id: 'fat_sep', label: 'מפריד שומן', en: 'FAT SEPARATOR' },
        { id: 'fat_line', label: 'קו למפריד', en: 'DRAIN LINE TO FAT SEPARATOR' },
        { id: 'air_pipe', label: 'קו אוויר', en: 'SEWAGE AIR PIPE' },
        { id: 'ground_fill', label: 'גובה מילוי ברצפה', en: 'GROUND FILLING FOR SEWAGE' },
        { id: 'water_asmade', label: 'תוכניות AS MADE', en: 'AS MADE PLANS' },
      ]
    },
    {
      id: 'electricity', label: 'חשמל', en: 'ELECTRICITY', color: '#ca8a04',
      items: [
        { id: 'power_feed', label: 'הזנה (גודל)', en: 'POWER FEED' },
        { id: 'grounding', label: 'הארקה ראשית של בניין', en: 'PRIMARY GROUNDING' },
        { id: 'supply_type', label: 'אופי הזנה — צובר/חח', en: 'PRIVATE OR GOVERNMENT SUPPLY' },
        { id: 'meter', label: 'מונה', en: 'METER' },
        { id: 'generator', label: 'חשמל חיוני/חרום', en: 'GENERATOR' },
        { id: 'elec_asmade', label: 'תוכניות AS MADE', en: 'AS MADE PLANS' },
      ]
    },
    {
      id: 'lowvoltage', label: 'מתח נמוך', en: 'LOW VOLTAGE', color: '#7c3aed',
      items: [
        { id: 'phone', label: 'בזק', en: 'PHONE SUPPLIER' },
        { id: 'network', label: 'תקשורת', en: 'NETWORK SUPPLIER' },
        { id: 'lv_other', label: 'אחר', en: 'OTHER' },
      ]
    },
    {
      id: 'gas', label: 'גז', en: 'GAS', color: '#dc2626',
      items: [
        { id: 'gas_feed', label: 'חיבור גז', en: 'GAS FEED' },
        { id: 'gas_supplier', label: 'ספק גז של מתחם', en: 'SUPPLIER' },
        { id: 'gas_valve', label: 'ברז חשמלי', en: 'ELECTRIC GAS FAUCET' },
        { id: 'gas_detector', label: 'גלאי גז', en: 'GAS DETECTOR' },
      ]
    },
    {
      id: 'air', label: 'מערכות אוויר', en: 'AIR SYSTEM', color: '#0d9488',
      items: [
        { id: 'ac', label: 'מיזוג', en: 'AIR CONDITION' },
        { id: 'filter', label: 'יחידת סינון', en: 'FILTER UNIT' },
        { id: 'fresh_air', label: 'אוויר צח', en: 'FRESH AIR' },
        { id: 'wc_vent', label: 'ונטות', en: 'WASHROOM VENTILATION' },
        { id: 'cooling_loc', label: 'מיקום חוות מנועי מקררים', en: 'GROUNDS FOR COOLING MOTORS' },
        { id: 'ac_loc', label: 'מיקום מנועי מיזוג', en: 'GROUNDS FOR AC MOTORS' },
        { id: 'smoke_release', label: 'מפוח שחרור עשן', en: 'SMOKE RELEASE SYSTEM' },
        { id: 'ac_supply', label: 'אופי הזנת מיזוג', en: 'AC SYSTEM TYPE' },
        { id: 'chimney', label: 'ארובה', en: 'CHIMNEY' },
        { id: 'air_asmade', label: 'תוכניות AS MADE', en: 'AS MADE PLANS' },
      ]
    },
    {
      id: 'fire', label: 'מערכות אש', en: 'FIRE SYSTEMS', color: '#ea580c',
      items: [
        { id: 'fire_detector', label: 'מערכת גלאים', en: 'FIRE DETECTOR' },
        { id: 'sprinklers', label: 'ספרינקלרים מעטפת', en: 'SPRINKLER SYSTEM' },
        { id: 'sprinkler_ctrl', label: 'מיקום ברז שליטה ספרינקלרים', en: 'SPRINKLER CONTROL' },
        { id: 'fire_pos', label: 'מיקום עמדות אש', en: 'FIRE POSITION' },
      ]
    },
    {
      id: 'facade', label: 'חזיתות', en: 'FACADE', color: '#4f46e5',
      items: [
        { id: 'vitrina', label: 'ויטרינה', en: 'FACADE' },
        { id: 'emergency_exit', label: 'יציאת חרום', en: 'EMERGENCY EXIT' },
        { id: 'signage', label: 'מפרט שילוט', en: 'SIGN REQUIREMENTS' },
        { id: 'facade_other', label: 'אחר', en: 'OTHER' },
      ]
    },
    {
      id: 'garbage', label: 'פינוי אשפה', en: 'GARBAGE DISPOSAL', color: '#65a30d',
      items: [
        { id: 'bins', label: 'פחים', en: 'PRIVATE BINS' },
        { id: 'dumpster', label: 'דחסנים', en: 'DUMP BINS' },
        { id: 'recycling', label: 'מיחזור', en: 'RECYCLING' },
        { id: 'garbage_other', label: 'אחר', en: 'OTHER' },
      ]
    },
  ];

  const [form, setForm] = useState(() => {
    try { return JSON.parse(localStorage.getItem(STORAGE_KEY)) || {}; } catch(e) { return {}; }
  });
  const [savedAt, setSavedAt] = useState(() => {
    try { const d = JSON.parse(localStorage.getItem(STORAGE_KEY)); return d?.__savedAt || null; } catch(e) { return null; }
  });

  const { isMobile, isLandscape } = useViewport();
  const tabBarH    = isMobile ? (isLandscape ? 48 : 60) : 0;
  const stickyBarH = 64;

  const upd = (key, val) => setForm(f => ({ ...f, [key]: val }));
  const updPhoto = (key, file) => {
    const reader = new FileReader();
    reader.onload = e => upd(key + '_photo', e.target.result);
    reader.readAsDataURL(file);
  };

  const save = (done = false) => {
    const data = { ...form, __savedAt: new Date().toISOString(), projectId, author: ((window.YBP_AUTH && window.YBP_AUTH.getCurrentUser) ? window.YBP_AUTH.getCurrentUser().name : YBP_DATA.user?.name) || 'מנהל' };
    localStorage.setItem(STORAGE_KEY, JSON.stringify(data));
    setSavedAt(data.__savedAt);
    if (done) {
      markBookletItemComplete(projectId, 'infra-survey');
      onComplete?.();
    } else {
      alert('נשמר בהצלחה ✓');
    }
  };

  const inp = { width:'100%', padding:'8px 10px', border:'1px solid #e5e7eb', borderRadius:6, fontSize:13, fontFamily:'inherit', background:'#fff', boxSizing:'border-box', direction:'rtl' };
  const lbl = { fontSize:10, fontWeight:600, color:'#6b7280', display:'block', marginBottom:3, textTransform:'uppercase', letterSpacing:0.4 };

  // ── PDF builder ───────────────────────────────────────────────────────────────
  const buildPdfParts = () => {
    const fmtD2 = iso => {
      if (!iso) return '—';
      const d = new Date(iso + 'T00:00:00');
      return String(d.getDate()).padStart(2,'0') + '/' +
             String(d.getMonth()+1).padStart(2,'0') + '/' + d.getFullYear();
    };
    const date      = form.date || new Date().toISOString().slice(0,10);
    const dateStr   = fmtD2(date);
    const surveyor  = form.surveyor || ((window.YBP_AUTH && window.YBP_AUTH.getCurrentUser) ? window.YBP_AUTH.getCurrentUser().name : YBP_DATA.user?.name) || '';
    const present   = form.present || '—';
    const asset     = form.asset || project?.name || '';

    const headerMetaHtml = `
      <div class="mb">
        <div><span class="badge">INFRA SURVEY</span></div>
        <div style="text-align:left">
          <div style="font-family:ui-monospace,Menlo,monospace;font-size:13px;font-weight:700;color:#1a2c4a">סקר תשתיות</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">סקר תשתיות — ${asset}</h2>
        ${project?.address ? `<div style="font-size:13px;color:#6b7280">${project.address}</div>` : ''}
      </div>
      <div class="sec" style="display:grid;grid-template-columns:repeat(3,1fr);gap:12px;padding:12px;background:#cffafe;border-radius:4px;border:1px solid #a5f3fc">
        <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">${surveyor}</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">${present}</div></div>
      </div>
    `;

    const sectionsHtml = SECTIONS.map(section => {
      const itemsRows = section.items.map(item => {
        const exist = form[`${section.id}_${item.id}_exist`] || '—';
        const note  = form[`${section.id}_${item.id}_note`]  || '';
        const photo = form[`${section.id}_${item.id}_photo`];
        const existColor = exist === 'קיים' ? '#16a34a' : exist === 'לא קיים' ? '#dc2626' : '#6b7280';
        return `
          <tr>
            <td style="font-weight:600">${item.label}<div style="font-size:9px;color:#9ca3af">${item.en}</div></td>
            <td style="text-align:center;color:${existColor};font-weight:700;font-size:10px">${exist}</td>
            <td style="font-size:10px;color:#4b5563">${note || '—'}</td>
            <td style="text-align:center">${photo ? `<img src="${photo}" style="max-width:60px;max-height:45px;object-fit:cover;border-radius:3px"/>` : '—'}</td>
          </tr>
        `;
      }).join('');
      const generalNote = form[`${section.id}_general_note`];
      return `
        <div class="sec">
          <div class="sec-lbl" style="background:${section.color};color:#fff;padding:5px 10px;border-radius:4px 4px 0 0">${section.label} · <span style="opacity:0.75">${section.en}</span></div>
          <table class="d" style="margin-top:0;border-radius:0 0 4px 4px">
            <thead><tr><th style="width:25%">פריט</th><th style="width:15%">קיים</th><th style="width:45%">הערות</th><th style="width:15%">תמונה</th></tr></thead>
            <tbody>${itemsRows}</tbody>
          </table>
          ${generalNote ? `<div style="padding:6px 10px;background:#f9fafb;font-size:10.5px;color:#4b5563;border-right:3px solid ${section.color};margin-top:4px"><strong>הערות כלליות:</strong> ${generalNote}</div>` : ''}
        </div>
      `;
    }).join('');

    const summaryHtml = (form.summary || form.recommendations) ? `
      <div class="sec"><div class="sec-lbl">סיכום ממצאים</div>
        ${form.summary ? `<div style="padding:10px;background:#fef3c7;border-radius:5px;font-size:11px;color:#713f12;border-right:3px solid #d97706;white-space:pre-wrap;margin-bottom:8px"><strong>ממצאים עיקריים:</strong><br>${form.summary}</div>` : ''}
        ${form.recommendations ? `<div style="padding:10px;background:#cffafe;border-radius:5px;font-size:11px;color:#0e7490;border-right:3px solid #0891b2;white-space:pre-wrap"><strong>המלצות לפעולה:</strong><br>${form.recommendations}</div>` : ''}
      </div>
    ` : '';

    return { headerMetaHtml, bodyHtml: sectionsHtml + summaryHtml };
  };

  // ── PDF / print handlers ──────────────────────────────────────────────────────
  const fmtFilename = () => {
    const date = form.date || new Date().toISOString().slice(0,10);
    const d = new Date(date + 'T00:00:00');
    const ds = String(d.getDate()).padStart(2,'0') + '-' + String(d.getMonth()+1).padStart(2,'0') + '-' + d.getFullYear();
    return `${ds}_${project?.name || ''}_סקר_תשתיות`;
  };

  const handlePreviewPdf = () => {
    if (typeof window.YBPPdf === 'undefined') { alert('מודול PDF לא טעון'); return; }
    const { headerMetaHtml, bodyHtml } = buildPdfParts();
    const logoSrc = document.querySelector('img[alt="YBP"]')?.src || '';
    window.YBPPdf.generatePdf({ orientation:'portrait', logoSrc, fileName: fmtFilename(), headerMetaHtml, bodyHtml, sigHtml:'', projectId, uploadToDrive:false });
  };

  const handlePrint = () => {
    if (typeof window.YBPPdf === 'undefined') { alert('מודול PDF לא טעון'); return; }
    const { headerMetaHtml, bodyHtml } = buildPdfParts();
    const logoSrc = document.querySelector('img[alt="YBP"]')?.src || '';
    window.YBPPdf.openPrintWindow({ orientation:'portrait', logoSrc, fileName: fmtFilename(), headerMetaHtml, bodyHtml, sigHtml:'' });
  };

  // ── Drive upload handler ──────────────────────────────────────────────────────
  const handleSaveToDrive = async () => {
    save(false);
    const getWebhookUrl = key => {
      try { const s = JSON.parse(localStorage.getItem('ybp_settings') || '{}'); return (s.webhooks || {})[key] || ''; }
      catch { return ''; }
    };
    const webhookUrl = getWebhookUrl('PLACEHOLDER_UPLOAD_REPORT_PDF')
      || 'https://hook.eu2.make.com/cwhco2m6u2m48ey692n7n7wagoz8cg0i';
    const sk = (() => {
      try { return JSON.parse(localStorage.getItem('ybp_settings') || '{}').webhooks?._securityKey || '1h4M4SEXbhoYF1YVW1mS6YJZs84yxSVHaBjPDDxMpbak'; }
      catch { return '1h4M4SEXbhoYF1YVW1mS6YJZs84yxSVHaBjPDDxMpbak'; }
    })();
    const { headerMetaHtml, bodyHtml } = buildPdfParts();
    const date = form.date || new Date().toISOString().slice(0,10);
    try {
      const resp = await fetch(webhookUrl, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          _sk: sk,
          manager: ((window.YBP_AUTH && window.YBP_AUTH.getCurrentUser) ? window.YBP_AUTH.getCurrentUser().name : YBP_DATA.user?.name) || 'מנהל',
          project: project?.name || '',
          project_id: projectId,
          drive_folder_id: project?.driveFolderId || '',
          type_name: 'סקר תשתיות',
          date,
          report_id: `infra-survey-${projectId}`,
          format: 'html',
          html: headerMetaHtml + bodyHtml,
        }),
      });
      if (resp.ok) {
        const data = await resp.json().catch(() => ({}));
        alert('✓ הסקר נשלח ל-Drive!\n📁 ' + (data.file_url || data.driveUrl || project?.name || ''));
      } else {
        alert('שגיאה בשליחה ל-Drive — בדוק webhook');
      }
    } catch { alert('⚠️ שגיאת חיבור ל-Drive'); }
  };

  // ── Share helpers ─────────────────────────────────────────────────────────────
  const buildShareText = () => {
    const date = form.date || new Date().toISOString().slice(0,10);
    const lines = [];
    lines.push(`📋 סקר תשתיות — ${project?.name || ''}`);
    lines.push(`תאריך: ${date}`);
    lines.push(`סוקר: ${form.surveyor || ((window.YBP_AUTH && window.YBP_AUTH.getCurrentUser) ? window.YBP_AUTH.getCurrentUser().name : YBP_DATA.user?.name) || ''}`);
    if (form.summary) { lines.push(''); lines.push('ממצאים עיקריים:'); lines.push(form.summary); }
    if (form.recommendations) { lines.push(''); lines.push('המלצות:'); lines.push(form.recommendations); }
    const issues = [];
    SECTIONS.forEach(section => {
      section.items.forEach(item => {
        const exist = form[`${section.id}_${item.id}_exist`];
        const note  = form[`${section.id}_${item.id}_note`];
        if (exist === 'לא קיים' || note) {
          issues.push(`• ${section.label} — ${item.label}: ${exist || ''}${note ? ' (' + note + ')' : ''}`);
        }
      });
    });
    if (issues.length) {
      lines.push('');
      lines.push(`ליקויים/הערות (${issues.length}):`);
      lines.push(...issues.slice(0, 20));
      if (issues.length > 20) lines.push(`... ועוד ${issues.length - 20}`);
    }
    return lines.join('\n');
  };

  const getDist = () => {
    try { return JSON.parse(localStorage.getItem(`ybp_dist_${projectId}`) || '{}'); } catch { return {}; }
  };

  const handleShareWA = () => {
    const txt = buildShareText();
    const dist = getDist();
    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');
  };

  const handleShareGmail = () => {
    const txt = buildShareText();
    const dist = getDist();
    const subject = `סקר תשתיות — ${project?.name || ''}`;
    window.open(`https://mail.google.com/mail/?view=cm&to=${encodeURIComponent(dist.emails || '')}&su=${encodeURIComponent(subject)}&body=${encodeURIComponent(txt)}`, '_blank');
  };

  const handleShareAll = () => { handleShareWA(); setTimeout(handleShareGmail, 300); };

  return (
    <div style={{ minHeight:'100%', background:'#f6f7f9', fontFamily:'Assistant, sans-serif', direction:'rtl', paddingBottom: tabBarH + stickyBarH + 16 }}>
      {/* Header */}
      <header style={{ background:'#1a2c4a', color:'#fff', padding:'0 16px', height:52, display:'flex', alignItems:'center', gap:12, position:'sticky', top:0, zIndex:10 }}>
        <button onClick={onBack} style={{ background:'transparent', border:'none', color:'#9ca3af', cursor:'pointer', padding:6 }}>
          <Icon name="chevronR" size={16}/>
        </button>
        <img src="assets/ybp-logo-new.png" alt="YBP" style={{ height:26, objectFit:'contain' }}/>
        <div style={{ flex:1 }}>
          <div style={{ fontSize:11, opacity:0.7 }}>{project?.name}</div>
          <div style={{ fontSize:14, fontWeight:700 }}>סקר תשתיות</div>
        </div>
        {savedAt && <div style={{ fontSize:11, opacity:0.6 }}>נשמר: {savedAt.slice(0,10)}</div>}
      </header>

      {/* PDF / Share toolbar */}
      <div style={{
        background:'#fff', borderBottom:'1px solid #e5e7eb',
        padding:'8px 12px',
        display:'flex', gap:8, flexWrap:'wrap',
      }}>
        {[
          { label:'תצוגת PDF',    icon:'👁️', onClick: handlePreviewPdf,  color:'#374151' },
          { label:'הדפס',         icon:'🖨️', onClick: handlePrint,       color:'#374151' },
          { label:'שמור ב-Drive', icon:'☁️', onClick: handleSaveToDrive, color:'#4338ca' },
          { label:'WhatsApp',     icon:'💬', onClick: handleShareWA,     color:'#16a34a' },
          { label:'Gmail',        icon:'✉️', onClick: handleShareGmail,  color:'#dc2626' },
          { label:'שלח הכל',      icon:'🚀', onClick: handleShareAll,    color:'#fff', bg:'#1a2c4a' },
        ].map(({ label, icon, onClick, color, bg }) => (
          <button key={label} onClick={onClick} style={{
            flex:'1 1 calc(33% - 6px)',
            minHeight:44, padding:'8px 10px',
            borderRadius:8,
            border: bg ? 'none' : '1px solid #e5e7eb',
            background: bg || '#fafbfc',
            color, fontSize:12, fontWeight:600,
            cursor:'pointer', fontFamily:'inherit',
            display:'flex', alignItems:'center', justifyContent:'center', gap:5,
          }}>
            <span style={{ fontSize:14 }}>{icon}</span>
            {label}
          </button>
        ))}
      </div>

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

        {/* Header fields */}
        <div style={{ background:'#fff', border:'1px solid #e5e7eb', borderRadius:10, padding:20, marginBottom:14 }}>
          <div style={{ fontSize:14, fontWeight:700, color:'#1a2c4a', marginBottom:14 }}>פרטי הסקר</div>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr 1fr', gap:12 }}>
            <div><label style={lbl}>נכס / Asset</label><input value={form.asset||''} onChange={e=>upd('asset',e.target.value)} style={inp} placeholder={project?.name}/></div>
            <div><label style={lbl}>סוקר / Surveyor</label><input value={form.surveyor || ((window.YBP_AUTH && window.YBP_AUTH.getCurrentUser) ? window.YBP_AUTH.getCurrentUser().name : YBP_DATA.user?.name) || ''} onChange={e=>upd('surveyor',e.target.value)} style={inp}/></div>
            <div><label style={lbl}>תאריך / Date</label><input type="date" value={form.date||new Date().toISOString().slice(0,10)} onChange={e=>upd('date',e.target.value)} style={inp}/></div>
            <div style={{ gridColumn:'span 3' }}><label style={lbl}>נוכחים / Present</label><input value={form.present||''} onChange={e=>upd('present',e.target.value)} style={inp} placeholder="שמות הנוכחים בסקר"/></div>
          </div>
        </div>

        {/* Sections */}
        {SECTIONS.map(section => (
          <div key={section.id} style={{ background:'#fff', border:'1px solid #e5e7eb', borderRadius:10, overflow:'hidden', marginBottom:14 }}>
            {/* Section header */}
            <div style={{ padding:'12px 18px', background:section.color, color:'#fff', display:'flex', alignItems:'center', gap:10 }}>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:14, fontWeight:700 }}>{section.label}</div>
                <div style={{ fontSize:11, opacity:0.75 }}>{section.en}</div>
              </div>
              <div style={{ fontSize:11, opacity:0.7 }}>קיים / הערות / תמונה</div>
            </div>

            {/* Items */}
            {section.items.map((item, i) => {
              const photoKey = `${section.id}_${item.id}_photo`;
              const noteKey = `${section.id}_${item.id}_note`;
              const existKey = `${section.id}_${item.id}_exist`;
              return (
                <div key={item.id} style={{ padding:'12px 18px', borderBottom: i < section.items.length-1 ? '1px solid #f3f4f6' : 'none' }}>
                  <div style={{ display:'grid', gridTemplateColumns:'1fr 160px 200px auto', gap:12, alignItems:'start' }}>
                    {/* Label */}
                    <div>
                      <div style={{ fontSize:13, fontWeight:600, color:'#1f2937' }}>{item.label}</div>
                      <div style={{ fontSize:11, color:'#9ca3af' }}>{item.en}</div>
                    </div>

                    {/* Existence — Yes/No/NA */}
                    <div style={{ display:'flex', gap:4 }}>
                      {['קיים','לא קיים','לא רלוונטי'].map(opt => (
                        <button key={opt} onClick={() => upd(existKey, opt)} style={{
                          flex:1, padding:'6px 4px', borderRadius:4, fontSize:11, fontWeight:600, cursor:'pointer', fontFamily:'inherit',
                          background: form[existKey] === opt ? section.color : '#fff',
                          color: form[existKey] === opt ? '#fff' : '#6b7280',
                          border: `1px solid ${form[existKey] === opt ? section.color : '#e5e7eb'}`,
                        }}>{opt === 'לא רלוונטי' ? 'N/A' : opt}</button>
                      ))}
                    </div>

                    {/* Note */}
                    <input
                      value={form[noteKey]||''}
                      onChange={e => upd(noteKey, e.target.value)}
                      placeholder="הערות / Remarks"
                      style={{ ...inp, fontSize:12 }}
                    />

                    {/* Photo */}
                    <div>
                      <PhotoPickerSheet onFiles={files => files[0] && updPhoto(`${section.id}_${item.id}`, files[0])}>
                        <div style={{ cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', width:38, height:38, borderRadius:6, border:'1px solid #e5e7eb', background:'#f9fafb', color:'#6b7280' }}>
                          {form[photoKey]
                            ? <img src={form[photoKey]} style={{ width:36, height:36, objectFit:'cover', borderRadius:5 }}/>
                            : <Icon name="camera" size={16}/>
                          }
                        </div>
                      </PhotoPickerSheet>
                    </div>
                  </div>
                </div>
              );
            })}

            {/* Section notes */}
            <div style={{ padding:'10px 18px 14px', background:'#fafbfc' }}>
              <input
                value={form[`${section.id}_general_note`]||''}
                onChange={e => upd(`${section.id}_general_note`, e.target.value)}
                placeholder={`הערות כלליות — ${section.label}`}
                style={{ ...inp, fontSize:12, background:'#fff' }}
              />
            </div>
          </div>
        ))}

        {/* Summary */}
        <div style={{ background:'#fff', border:'1px solid #e5e7eb', borderRadius:10, padding:20, marginBottom:14 }}>
          <div style={{ fontSize:14, fontWeight:700, color:'#1a2c4a', marginBottom:14 }}>סיכום ממצאים</div>
          <div style={{ marginBottom:12 }}>
            <label style={lbl}>ממצאים עיקריים</label>
            <textarea value={form.summary||''} onChange={e=>upd('summary',e.target.value)} rows={4} style={{ ...inp, resize:'vertical' }} placeholder="תאר את הממצאים העיקריים שנמצאו בסקר..."/>
          </div>
          <div>
            <label style={lbl}>המלצות לפעולה</label>
            <textarea value={form.recommendations||''} onChange={e=>upd('recommendations',e.target.value)} rows={3} style={{ ...inp, resize:'vertical' }} placeholder="פעולות נדרשות לפני תחילת עבודה..."/>
          </div>
        </div>
      </div>

      {/* Sticky bar */}
      <div style={{ position:'fixed', bottom: tabBarH, insetInline:0, background:'#1a2c4a', padding:'12px 20px', display:'flex', alignItems:'center', gap:10, zIndex: 8300, paddingBottom:`calc(12px + env(safe-area-inset-bottom, 0px))` }}>
        <div style={{ flex:1, fontSize:12, color:'rgba(255,255,255,0.6)' }}>
          {savedAt ? `נשמר לאחרונה: ${savedAt.slice(0,16).replace('T',' ')}` : 'טרם נשמר'}
        </div>
        <button onClick={() => save(false)} style={{ padding:'9px 18px', borderRadius:6, border:'1px solid rgba(255,255,255,0.3)', background:'transparent', color:'#fff', fontSize:13, cursor:'pointer', fontFamily:'inherit' }}>
          שמור ✓
        </button>
        <button onClick={() => save(true)} style={{ padding:'9px 18px', borderRadius:6, border:'none', background:'#10b981', color:'#fff', fontSize:13, fontWeight:700, cursor:'pointer', fontFamily:'inherit' }}>
          אשר וסמן כהושלם →
        </button>
      </div>
    </div>
  );
};

Object.assign(window, { BookletScreen, ClientDetailsForm, InfraSurveyForm });
// v63 — חשיפת loadBooklet לגאנט (מקור משימות החוברת האמיתיות)
window.YBP_BOOKLET = { loadBooklet };
})();
