// Infra Documentation Report — תיעוד תשתיות
(function(){
const { useState, useRef } = React;

const INFRA_TYPES = [
  { k:'foundation',  label:'יסודות ושלד',        icon:'🏗️' },
  { k:'envelope',    label:'מעטפת (קירות/חלונות)',icon:'🧱' },
  { k:'plumbing',    label:'אינסטלציה',            icon:'🔧' },
  { k:'electric',    label:'חשמל',                 icon:'⚡' },
  { k:'lowvoltage',  label:'מתח נמוך / תקשורת',   icon:'📡' },
  { k:'gas',         label:'גז',                   icon:'🔥' },
  { k:'hvac',        label:'מיזוג אוויר',           icon:'❄️' },
  { k:'fire',        label:'אש וגילוי עשן',        icon:'🚿' },
  { k:'plaster',     label:'טיח וגבס',             icon:'🪣' },
  { k:'flooring',    label:'ריצוף ואריחים',        icon:'⬜' },
  { k:'facade',      label:'חזיתות',               icon:'🏢' },
  { k:'drainage',    label:'ניקוז וביוב',           icon:'🌊' },
  { k:'insulation',  label:'איטום',                icon:'🛡️' },
  { k:'other',       label:'אחר',                  icon:'📋' },
];

const STATUS_OPTS = [
  { k:'ok',       label:'תקין',         color:'#10b981', bg:'#d1fae5' },
  { k:'issue',    label:'טעון טיפול',   color:'#f59e0b', bg:'#fef3c7' },
  { k:'critical', label:'בעיה קריטית',  color:'#dc2626', bg:'#fee2e2' },
];

const compressPhoto = (file, cb) => {
  const reader = new FileReader();
  reader.onload = e => {
    const img = new Image();
    img.onload = () => {
      const MAX = 1200;
      const ratio = Math.min(1, MAX / Math.max(img.width, img.height));
      const canvas = document.createElement('canvas');
      canvas.width = Math.round(img.width * ratio);
      canvas.height = Math.round(img.height * ratio);
      canvas.getContext('2d').drawImage(img, 0, 0, canvas.width, canvas.height);
      cb(canvas.toDataURL('image/jpeg', 0.72));
    };
    img.src = e.target.result;
  };
  reader.readAsDataURL(file);
};

// ── תצלום בודד (thumbnail + delete) ──────────────────────────────────────────
const PhotoThumb = ({ src, onRemove }) => (
  <div style={{ position:'relative', width:72, height:72 }}>
    <img src={src} alt="" style={{ width:72, height:72, objectFit:'cover', borderRadius:7, border:'1px solid #e5e7eb' }}/>
    <button onClick={onRemove} style={{
      position:'absolute', top:-6, left:-6, width:18, height:18, borderRadius:9,
      background:'#dc2626', color:'#fff', border:'none', cursor:'pointer',
      fontSize:11, lineHeight:'18px', textAlign:'center', padding:0,
    }}>✕</button>
  </div>
);

// ── כרטיס ממצא תשתית ──────────────────────────────────────────────────────────
const InfraCard = ({ item, idx, onChange, onRemove }) => {
  const fileRef = useRef();
  const [expanded, setExpanded] = useState(true);
  const { isMobile } = window.useViewport ? window.useViewport() : { isMobile: false };
  const infra = INFRA_TYPES.find(t => t.k === item.infraType) || INFRA_TYPES[0];
  const status = STATUS_OPTS.find(s => s.k === item.status) || STATUS_OPTS[0];

  const addPhotos = (files) => {
    Array.from(files).forEach(f => compressPhoto(f, ph => {
      onChange({ ...item, photos: [...(item.photos || []), ph] });
    }));
  };

  return (
    <div style={{
      background:'#fff', border:`1px solid ${status.color}`,
      borderRadius:10, overflow:'hidden',
      boxShadow:`0 0 0 3px ${status.bg}`,
    }}>
      {/* Header */}
      <div style={{ display:'flex', alignItems:'center', gap:8, padding:'10px 12px', background:'#fafbfc', borderBottom:`1px solid ${status.bg}`, flexWrap: isMobile ? 'wrap' : 'nowrap' }}>
        <div style={{
          width:28, height:28, borderRadius:7, background:status.bg, color:status.color,
          fontSize:13, fontWeight:800, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0,
        }}>{idx + 1}</div>
        <span style={{ fontSize:18, flexShrink:0 }}>{infra.icon}</span>
        <select value={item.infraType || ''} onChange={e => onChange({ ...item, infraType: e.target.value })}
          style={{ flex:1, minWidth:0, border:'none', background:'transparent', fontSize:13, fontWeight:700, color:'#1f2937', fontFamily:'inherit', cursor:'pointer', outline:'none' }}>
          {INFRA_TYPES.map(t => <option key={t.k} value={t.k}>{t.icon} {t.label}</option>)}
        </select>
        <div style={{ display:'flex', gap:4, flexWrap:'wrap', flexShrink:0 }}>
          {STATUS_OPTS.map(s => (
            <button key={s.k} onClick={() => onChange({ ...item, status: s.k })} style={{
              padding:'3px 8px', borderRadius:10, border:`1px solid ${item.status===s.k ? s.color : '#e5e7eb'}`,
              background: item.status===s.k ? s.bg : '#fff', color: item.status===s.k ? s.color : '#9ca3af',
              fontSize:10, fontWeight:700, cursor:'pointer', fontFamily:'inherit', whiteSpace:'nowrap',
            }}>{s.label}</button>
          ))}
        </div>
        <button onClick={() => setExpanded(!expanded)} style={{ background:'transparent', border:'none', cursor:'pointer', color:'#6b7280', padding:4, flexShrink:0 }}>
          <Icon name={expanded ? 'chevronD' : 'chevron'} size={16}/>
        </button>
        <button onClick={onRemove} style={{ background:'transparent', border:'none', cursor:'pointer', color:'#dc2626', padding:4, flexShrink:0 }}>
          <Icon name="close" size={16}/>
        </button>
      </div>

      {expanded && (
        <div style={{ padding:14, display:'flex', flexDirection:'column', gap:12 }}>
          {/* מיקום */}
          <div>
            <label style={{ fontSize:11, fontWeight:700, color:'#6b7280', display:'block', marginBottom:5 }}>מיקום באתר</label>
            <input value={item.location || ''} onChange={e => onChange({ ...item, location: e.target.value })}
              placeholder="למשל: קיר צפוני, חדר 3, תקרת מטבח..."
              style={{ width:'100%', padding:'8px 10px', border:'1px solid #e5e7eb', borderRadius:6, fontSize:13, fontFamily:'inherit', boxSizing:'border-box' }}/>
          </div>

          {/* תיאור */}
          <div>
            <label style={{ fontSize:11, fontWeight:700, color:'#6b7280', display:'block', marginBottom:5 }}>תיאור / ממצא</label>
            <textarea value={item.description || ''} onChange={e => onChange({ ...item, description: e.target.value })}
              rows={2} placeholder="תאר את מצב התשתית, מה בוצע, מה צריך טיפול..."
              style={{ width:'100%', padding:'8px 10px', border:'1px solid #e5e7eb', borderRadius:6, fontSize:13, fontFamily:'inherit', resize:'vertical', boxSizing:'border-box' }}/>
          </div>

          {/* תמונות */}
          <div>
            <label style={{ fontSize:11, fontWeight:700, color:'#6b7280', display:'block', marginBottom:8 }}>תמונות תיעוד</label>
            <div style={{ display:'flex', flexWrap:'wrap', gap:8, alignItems:'center' }}>
              {(item.photos || []).map((ph, pi) => (
                <PhotoThumb key={pi} src={ph} onRemove={() => onChange({ ...item, photos: item.photos.filter((_,j) => j !== pi) })}/>
              ))}
              <PhotoPickerInline onFiles={files => addPhotos(files)} multiple/>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

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

// ── Main Form ──────────────────────────────────────────────────────────────────
const InfraDocForm = ({ projectId, prefillData, onBack, onAfterSubmit }) => {
  const project = YBP_DATA.projects.find(p => p.id === projectId) || YBP_DATA.projects[0];
  const today = new Date().toISOString().slice(0, 10);
  const { isMobile } = window.useViewport ? window.useViewport() : { isMobile: false };
  const [submittedReport, setSubmittedReport] = React.useState(null);

  const [stage, setStage]       = useState('');
  const [location, setLocation] = useState('');
  const [notes, setNotes]       = useState(prefillData ? (prefillData.structured?.notes || prefillData.summaryText || '') : '');
  const [items, setItems]       = useState(() => {
    if (prefillData?.structured?.items?.length) {
      return prefillData.structured.items.map((it, i) => ({
        id: `i-${Date.now()}-${i}`,
        infraType: it.infraType || 'other',
        status:    it.status === 'issue' || it.status === 'critical' ? it.status : 'ok',
        location:  it.location || '',
        description: it.description || '',
        photos: [],
      }));
    }
    return [{ id:`i-${Date.now()}`, infraType:'plumbing', status:'ok', location:'', description:'', photos:[] }];
  });
  const [submitting, setSubmitting] = useState(false);
  const draftKey           = `ybp_draft_infra_${projectId}`;
  const [draftSavedAt, setDraftSavedAt] = useState(null);
  const restorePromptShown = React.useRef(false);

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

  // סנכרן draft מ-Supabase בעלייה (cross-device)
  useEffect(() => {
    if (restorePromptShown.current) return;
    restorePromptShown.current = true;
    (async () => {
      try {
        const cloudResult = await window.loadDraftFromSupabase?.({ kind: 'infra', projectId });
        if (cloudResult?.formData?.savedAt) {
          const local = window.cloudLoadSync ? window.cloudLoadSync(draftKey) : null;
          if ((cloudResult.formData.savedAt || 0) > (local?.savedAt || 0)) {
            if (cloudResult.formData.stage !== undefined) setStage(cloudResult.formData.stage);
            if (cloudResult.formData.location !== undefined) setLocation(cloudResult.formData.location);
            if (cloudResult.formData.notes !== undefined) setNotes(cloudResult.formData.notes);
            await window.cloudSave?.(draftKey, cloudResult.formData);
          }
        }
      } catch (_) {}
      // Show draft age indicator from localStorage
      const local = window.cloudLoadSync ? window.cloudLoadSync(draftKey) : null;
      if (local?.savedAt) setDraftSavedAt(local.savedAt);
    })();
  }, []); // eslint-disable-line react-hooks/exhaustive-deps

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

  // ── Voice fill listener ───────────────────────────────────────────────────
  React.useEffect(() => {
    const handler = (e) => {
      const { formType, data } = e.detail || {};
      if (formType !== 'infra' || !data) return;
      if (data.notes) setNotes(data.notes);
      if (data.location) setLocation(data.location);
      // עדכן פריט ראשון עם נתונים מהדיבור
      if (data.issues || data.systemType) {
        setItems(prev => {
          const updated = [...prev];
          if (updated.length > 0) {
            updated[0] = {
              ...updated[0],
              description: data.issues || updated[0].description,
              location: data.location || updated[0].location,
              infraType: mapSystemType(data.systemType) || updated[0].infraType,
              status: data.issues ? 'issue' : updated[0].status,
            };
          }
          return updated;
        });
      }
    };

    const mapSystemType = (type) => {
      if (!type) return null;
      if (type.includes('חשמל')) return 'electric';
      if (type.includes('אינסטלציה') || type.includes('מים')) return 'plumbing';
      if (type.includes('מיזוג')) return 'hvac';
      if (type.includes('כיבוי') || type.includes('אש')) return 'fire';
      if (type.includes('גז')) return 'gas';
      if (type.includes('ריצוף')) return 'flooring';
      return null;
    };

    window.addEventListener('ybp-voice-fill', handler);
    return () => window.removeEventListener('ybp-voice-fill', handler);
  }, []);

  const addItem = () => setItems(prev => [...prev, {
    id: `i-${Date.now()}`, infraType: 'electric', status: 'ok', location: '', description: '', photos: [],
  }]);

  const updateItem = (id, data) => setItems(prev => prev.map(x => x.id === id ? data : x));
  const removeItem = (id) => setItems(prev => prev.filter(x => x.id !== id));

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

  const handleSubmit = async () => {
    if (submitting) return;
    setSubmitting(true);
    try {
      const photoWh = (function() {
        try {
          const s = JSON.parse(localStorage.getItem('ybp_settings') || '{}');
          return (s.webhooks && s.webhooks.PLACEHOLDER_UPLOAD_PHOTO) || 'https://hook.eu2.make.com/od77j53zjvkzdc5rsyfpjfpg6rjuz4e4';
        } catch (_) { return 'https://hook.eu2.make.com/od77j53zjvkzdc5rsyfpjfpg6rjuz4e4'; }
      })();
      const sk = '1h4M4SEXbhoYF1YVW1mS6YJZs84yxSVHaBjPDDxMpbak';
      const pmName = (window.YBP_AUTH && window.YBP_AUTH.getCurrentUser) ? window.YBP_AUTH.getCurrentUser().name : (YBP_DATA.user && YBP_DATA.user.name) || 'מנהל';
      const projectName = YBP_DATA.projects.find(p => p.id === projectId)?.name || '';
      const hasBase64 = items.some(item => (item.photos || []).some(p => p && p.startsWith('data:')));
      if (hasBase64 && window.toastInfo) window.toastInfo('מעלה תמונות ל-Drive...');
      const uploadedItems = await Promise.all(items.map(async function(item) {
        const cleanPhotos = await Promise.all((item.photos || []).map(async function(photo, idx) {
          if (!photo || !photo.startsWith('data:')) return photo;
          try {
            const base64 = photo.replace(/^data:[^;]+;base64,/, '');
            const controller = new AbortController();
            const timeoutId = setTimeout(function() { controller.abort(); }, 15000);
            const resp = await fetch(photoWh, {
              method: 'POST',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({
                _sk: sk, manager: pmName, project: projectName, projectId,
                rejection_name: item.infraType || 'תשתית',
                date: today, photo_index: idx, image_base64: base64,
              }),
              signal: controller.signal,
            });
            clearTimeout(timeoutId);
            const json = await resp.json();
            return json.url || json.drive_url || json.fileUrl || photo;
          } catch (_) { return photo; }
        }));
        return Object.assign({}, item, { photos: cleanPhotos });
      }));
      if (hasBase64 && window.toastSuccess) window.toastSuccess('תמונות הועלו ✓');

      const id = SyncStore.nextReportId(projectId, 'infra');
      const report = {
        id, kind: 'infra', projectId,
        title: `תיעוד תשתיות${stage ? ` — ${stage}` : ''} · ${fmtDateHe(today)}`,
        date: today,
        author: pmName,
        content: { stage, location, notes, items: uploadedItems },
        rejects: [],
      };
      await SyncStore.submitSiteReport(report);
      window.markDraftSent?.(draftKey);
      if (window.cloudSave) window.cloudSave(draftKey, null).catch(() => {});
      else { try { localStorage.removeItem(draftKey); } catch (_) {} }
      if (prefillData?.summaryId) {
        window.PendingSummariesAPI?.approveUsed(prefillData.summaryId);
      }
      setSubmittedReport(report);
      if (window.toastSuccess) window.toastSuccess('דוח תשתיות נוצר ✓');
      onAfterSubmit ? onAfterSubmit(report) : onBack();
    } catch (e) {
      if (window.toastError) window.toastError('שגיאה ביצירת הדוח');
      console.error('[InfraDoc] handleSubmit error:', e);
    } finally {
      setSubmitting(false);
    }
  };

  const fmtDateHe = window.fmtDateHe || ((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 totalPhotos = items.reduce((sum, i) => sum + (i.photos || []).length, 0);
  const issueCount  = items.filter(i => i.status === 'issue' || i.status === 'critical').length;

  return (
    <div style={{ minHeight:'100%', background:'#f6f7f9', fontFamily:'Assistant, sans-serif', direction:'rtl', overflowX:'hidden' }}>
      {/* TODO(photos): פיצ'ר הוספת תמונות אחרי דוח הוסר ב-v3.9.0.41 — צריך לתכנן מחדש זרימת תמונות→Drive. */}
      {/* Header */}
      <header style={{
        background:'#fff', borderBottom:'1px solid #e5e7eb',
        padding: isMobile ? '10px 12px' : '12px 20px',
        display:'flex', alignItems:'center', gap:10, position:'sticky', top:0, zIndex:10,
        flexWrap: isMobile ? 'wrap' : 'nowrap',
      }}>
        <button onClick={onBack} style={{
          background:'transparent', border:'none', cursor:'pointer', color:'#6b7280',
          display:'flex', alignItems:'center', gap:4, fontSize:14, padding:6, fontFamily:'inherit', flexShrink:0,
        }}>
          <Icon name="chevron" size={18}/> חזרה
        </button>
        <div style={{ width:1, height:24, background:'#e5e7eb', flexShrink:0 }}/>
        <span style={{ fontSize:15, fontWeight:700, color:'#1f2937' }}>תיעוד תשתיות</span>
        {!isMobile && (
          <span style={{ padding:'3px 10px', borderRadius:12, fontSize:11, fontWeight:700, background:'#fdf4ff', color:'#9333ea' }}>
            🏗️ תשתיות
          </span>
        )}
        <div style={{ flex:1 }}/>
        {/* Stats */}
        <div style={{ display:'flex', gap: isMobile ? 8 : 12, fontSize:12, color:'#6b7280', flexShrink:0 }}>
          <span>{items.length} סעיפים</span>
          <span>📷 {totalPhotos}</span>
          {issueCount > 0 && <span style={{ color:'#dc2626', fontWeight:700 }}>⚠️ {issueCount}</span>}
        </div>
      </header>

      <div style={{ maxWidth:680, margin:'0 auto', padding: isMobile ? '14px 12px' : '20px 16px' }}>

        {/* Draft age indicator */}
        {draftSavedAt && (
          <div style={{ display:'flex', alignItems:'center', gap:8, fontSize:12, color:'#92400e', background:'#fffbeb', border:'1px solid #fbbf24', borderRadius:8, padding:'8px 12px', marginBottom:12 }}>
            <span>📋</span>
            <span>טיוטה שמורה — {formatDraftAge(draftSavedAt)}</span>
          </div>
        )}

        {/* פרטים כלליים */}
        <div style={{ background:'#fff', border:'1px solid #e5e7eb', borderRadius:10, padding:16, marginBottom:16 }}>
          <div style={{ fontSize:13, fontWeight:700, color:'#1f2937', marginBottom:12 }}>פרטים כלליים</div>
          <div style={{ display:'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap:12 }}>
            <div>
              <label style={{ fontSize:11, fontWeight:700, color:'#6b7280', display:'block', marginBottom:5 }}>שלב תשתית</label>
              <input value={stage} onChange={e => setStage(e.target.value)}
                placeholder='למשל: "שלב א — תשתיות ראשוניות"'
                style={{ width:'100%', padding:'9px 10px', border:'1px solid #e5e7eb', borderRadius:6, fontSize:13, fontFamily:'inherit', boxSizing:'border-box' }}/>
            </div>
            <div>
              <label style={{ fontSize:11, fontWeight:700, color:'#6b7280', display:'block', marginBottom:5 }}>מיקום כללי באתר</label>
              <input value={location} onChange={e => setLocation(e.target.value)}
                placeholder="קומה, אזור, חדר..."
                style={{ width:'100%', padding:'9px 10px', border:'1px solid #e5e7eb', borderRadius:6, fontSize:13, fontFamily:'inherit', boxSizing:'border-box' }}/>
            </div>
          </div>
        </div>

        {/* ממצאי תשתית */}
        <div style={{ display:'flex', flexDirection:'column', gap:10, marginBottom:16 }}>
          {items.map((item, i) => (
            <InfraCard
              key={item.id}
              item={item}
              idx={i}
              onChange={data => updateItem(item.id, data)}
              onRemove={() => removeItem(item.id)}
            />
          ))}

          <button onClick={addItem} style={{
            padding:'13px', borderRadius:8, border:'2px dashed #c4b5fd',
            background:'#faf5ff', color:'#7c3aed', fontSize:13, fontWeight:600,
            cursor:'pointer', fontFamily:'inherit', display:'flex', alignItems:'center',
            justifyContent:'center', gap:6,
          }}>
            <Icon name="plus" size={16}/> הוסף סעיף תשתית
          </button>
        </div>

        {/* הערות */}
        <div style={{ background:'#fff', border:'1px solid #e5e7eb', borderRadius:10, padding:16, marginBottom:20 }}>
          <div style={{ fontSize:13, fontWeight:700, color:'#1f2937', marginBottom:10 }}>הערות כלליות לדוח</div>
          <textarea value={notes} onChange={e => setNotes(e.target.value)} rows={3}
            placeholder="הערות נוספות, דרישות מיוחדות, ממצאים לדגש..."
            style={{ width:'100%', padding:'10px 12px', borderRadius:6, border:'1px solid #e5e7eb', fontSize:13, fontFamily:'inherit', resize:'vertical', boxSizing:'border-box' }}/>
        </div>

      </div>

      {/* Sticky action bar */}
      <div style={{
        position:'sticky', bottom:0, background:'#fff',
        borderTop:'1px solid #e5e7eb', padding: isMobile ? '10px 12px' : '12px 24px',
        zIndex:800, display:'flex', alignItems:'center', gap:12, justifyContent:'space-between',
        marginTop:8,
      }}>
        <div style={{ fontSize:12, color:'#6b7280' }}>
          {items.length} סעיפים · {totalPhotos} תמונות
          {issueCount > 0 && <span style={{ color:'#dc2626', fontWeight:700, marginRight:8 }}> · ⚠️ {issueCount} ממצאים</span>}
        </div>
        <div style={{ display:'flex', gap:8 }}>
          <button onClick={handleDeleteDraft} style={{
            padding:'9px 14px', borderRadius:6,
            border:'1px solid var(--ybp-danger-bg,#fecaca)',
            background:'var(--ybp-panel,#fff)', color:'var(--ybp-danger,#dc2626)',
            fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:'inherit',
            display:'flex', alignItems:'center', gap:6,
          }}>🗑 מחק טיוטה</button>
          <button onClick={onBack} style={{
            padding:'9px 18px', borderRadius:6, border:'1px solid #e5e7eb', background:'#fff',
            color:'#6b7280', fontSize:13, fontWeight:600, cursor:'pointer', fontFamily:'inherit',
          }}>ביטול</button>
          <button onClick={handleSubmit} disabled={submitting} style={{
            padding:'9px 18px', borderRadius:6, border:'none',
            background: submitting ? '#9ca3af' : '#9333ea',
            color:'#fff', fontSize:13, fontWeight:700, cursor:'pointer', fontFamily:'inherit',
            display:'flex', alignItems:'center', gap:6,
          }}>
            <Icon name="send" size={14}/> {submitting ? 'יוצר...' : 'צור דוח'}
          </button>
        </div>
      </div>
    </div>
  );
};

window.InfraDocForm = InfraDocForm;
})();
