// Meeting summary screen v2 — auto-fill, attendee dropdown+manual, findings with photos, report numbering
(function(){
const { useState, useEffect, useRef } = React;

const SAMPLE_FINDINGS = [];

const SEVERITY_STYLES = {
  high:   { bg: '#fee2e2', fg: '#991b1b', label: 'גבוהה', dot: '#dc2626' },
  medium: { bg: '#fef3c7', fg: '#b45309', label: 'בינונית', dot: '#f59e0b' },
  low:    { bg: '#dbeafe', fg: '#1e40af', label: 'נמוכה', dot: '#3b82f6' },
};

// ============================================================
// SCREEN 1: Meeting form (improved)
// ============================================================

// ── DecisionInput — שדה הוספת החלטה ──────────────────────────────────────
const DecisionInput = ({ onAdd, inputStyle }) => {
  const [val, setVal] = React.useState('');
  const add = () => { if (val.trim()) { onAdd(val.trim()); setVal(''); } };
  return (
    <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
      <input
        style={{ ...inputStyle, flex: 1 }}
        placeholder="הוסף החלטה..."
        value={val}
        onChange={e => setVal(e.target.value)}
        onKeyDown={e => { if (e.key === 'Enter') add(); }}
      />
      <button
        onClick={add}
        style={{ background: '#10b981', color: '#fff', border: 'none', borderRadius: 6, padding: '0 14px', fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', flexShrink: 0 }}>
        + הוסף
      </button>
    </div>
  );
};

const MeetingFormScreen = ({ projectId = '', onBack, onAfterSubmit, onOpenRecorder, onNav }) => {
  const project = YBP_DATA.projects.find(p => p.id === projectId) || YBP_DATA.projects[0];
  const contacts = YBP_DATA.projectDetail.contacts || [];
  const [submittedMeeting, setSubmittedMeeting] = React.useState(null);

  // Auto-filled report number
  const [reportId] = useState(() => 'meeting_' + projectId + '_' + Date.now().toString(36));

  // Auto-filled meta from project
  const today = new Date().toISOString().slice(0, 10);
  const [meta, setMeta] = useState({
    title: 'סיכום פגישת תיאום שבועית',
    date: today,
    time: '10:00',
    duration: 90,
    location: project.address, // AUTO from project
    author: ((window.YBP_AUTH && window.YBP_AUTH.getCurrentUser) ? window.YBP_AUTH.getCurrentUser().name : YBP_DATA.user?.name) || 'מנהל פרויקט',
  });

  const [attendees, setAttendees] = useState([]);
  const [agenda, setAgenda] = useState([]);
  const [agendaInput, setAgendaInput] = useState("");
  const [discussion] = useState([]);
  const [decisions, setDecisions] = useState([]);

  const [findings, setFindings] = useState(SAMPLE_FINDINGS.map(f => ({
    ...f,
    due: window.defaultDueDate(),
  })));

  const [nextMeeting, setNextMeeting] = useState({
    date: '2026-04-25',
    time: '10:00',
    location: project.address,
    title: `פגישת תיאום — ${project.name}`,
  });

  // ===== Attendee picker =====
  const [showPicker, setShowPicker] = useState(false);
  const [manualMode, setManualMode] = useState(false);
  const [manualContact, setManualContact] = useState({ name: '', role: '', company: '', email: '', phone: '' });

  // ── Voice fill listener ───────────────────────────────────────────────────
  useEffect(() => {
    const handler = (e) => {
      const { formType, data } = e.detail || {};
      if (formType !== 'meeting' || !data) return;
      if (data.title) setMeta(prev => ({ ...prev, title: data.title }));
      if (data.location) setMeta(prev => ({ ...prev, location: data.location }));
      if (data.nextMeetingDate) setNextMeeting(prev => ({ ...prev, date: data.nextMeetingDate }));
      if (data.decision) setDecisions(prev => [...prev, data.decision]);
      if (data.findingTitle) {
        setFindings(prev => [...prev, {
          id: `f-voice-${Date.now()}`,
          title: data.findingTitle,
          description: data.findingDescription || '',
          location: data.location || '',
          assignee: data.findingAssignee || contacts[0]?.name || '',
          severity: 'medium',
          photo: null,
          due: data.findingDue || window.defaultDueDate?.() || '',
        }]);
      }
    };
    window.addEventListener('ybp-voice-fill', handler);
    return () => window.removeEventListener('ybp-voice-fill', handler);
  }, [contacts]);

  // auto-save draft
  useEffect(() => {
    const draftKey = 'meeting_' + projectId;
    const timer = setTimeout(() => {
      if (window.cloudSave) window.cloudSave(draftKey, { meta, decisions });
    }, 1500);
    return () => clearTimeout(timer);
  }, [meta, decisions, projectId]);

  const addFromContacts = (c) => {
    if (!attendees.find(a => a.id === c.id)) setAttendees([...attendees, c]);
    setShowPicker(false);
  };
  const addManual = () => {
    if (!manualContact.name) return;
    setAttendees([...attendees, { ...manualContact, id: `manual-${Date.now()}`, type: 'manual' }]);
    setManualContact({ name: '', role: '', company: '', email: '', phone: '' });
    setManualMode(false);
    setShowPicker(false);
  };
  const removeAttendee = (id) => setAttendees(attendees.filter(a => a.id !== id));

  const available = contacts.filter(c => !attendees.find(a => a.id === c.id));

  // ===== Findings management =====
  const updateFinding = (id, patch) => {
    setFindings(findings.map(f => f.id === id ? { ...f, ...patch } : f));
  };
  const removeFinding = (id) => setFindings(findings.filter(f => f.id !== id));
  const addFinding = () => {
    setFindings([...findings, {
      id: `f-${Date.now()}`,
      title: '',
      description: '',
      location: '',
      assignee: contacts[0]?.name || '',
      severity: 'medium',
      photo: null,
      due: window.defaultDueDate(),
    }]);
  };
  const handlePhotoUpload = (id, file) => {
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (e) => updateFinding(id, { photo: e.target.result });
    reader.readAsDataURL(file);
  };

  // ===== Submit =====
  const handleSubmit = () => {
    const report = {
      id: reportId,
      projectId,
      kind: 'meeting',
      type: 'meeting',
      title: meta.title,
      date: meta.date,
      author: meta.author,
      meta,
      attendees,
      agenda,
      discussion,
      decisions,
      findings: findings.filter(f => f.title), // only real findings
      nextMeeting,
    };
    // שמור ב-localStorage כ-fallback offline
    try { SyncStore.submitReport(report); } catch(e) {}

    // שמור ב-Supabase
    const draftKey = 'meeting_' + projectId;
    if (window.saveReportAsSent) {
      window.saveReportAsSent(draftKey, report).then(res => {
        if (!res.ok) console.warn('[Meeting] cloud save failed:', res.error);
      });
    }
    setSubmittedMeeting(report);
    if (onAfterSubmit) onAfterSubmit(report);
  };

  // ===== Gmail send =====
  const handleSendEmail = () => {
    const recipients = [
      ...contacts.map(c => c.email),
      ...attendees.filter(a => a.type === 'manual' && a.email).map(a => a.email),
    ];
    const body = `שלום,\n\nמצורף סיכום הפגישה: ${meta.title}\nפרויקט: ${project.name}\nתאריך: ${meta.date}\n\nלצפייה בדוח האינטראקטיבי (כולל סימון משימות כבוצעו, שינוי תאריכים והוספת הערות):\nhttps://ybp.app/r/${reportId}/view\n\nבברכה,\n${meta.author}\nYBPROJECTS`;
    const url = window.buildGmailUrl({
      to: recipients,
      subject: `${project.name} — ${meta.title}`,
      body,
    });
    window.open(url, '_blank');
  };

  // ===== Styles =====
  const inputStyle = {
    width: '100%', padding: '8px 10px', border: '1px solid var(--v1-border)',
    borderRadius: 5, fontSize: 13, fontFamily: 'inherit', background: '#fff',
    color: 'var(--v1-ink)', outline: 'none',
  };
  const inputReadOnly = { ...inputStyle, background: '#f9fafb', color: '#6b7280' };
  const labelStyle = {
    fontSize: 11, fontWeight: 600, color: 'var(--v1-ink-soft)',
    textTransform: 'uppercase', letterSpacing: 0.3, marginBottom: 5, display: 'block',
  };
  const sectionTitle = {
    fontSize: 14, fontWeight: 700, color: 'var(--v1-ink)',
    margin: '0 0 14px', display: 'flex', alignItems: 'center', gap: 8,
  };
  const card = {
    background: '#fff', border: '1px solid var(--v1-border)', borderRadius: 10,
    padding: 20, marginBottom: 14,
  };
  const stepNum = (n, color = 'var(--v1-accent)') => ({
    background: color, color: '#fff', width: 22, height: 22, borderRadius: 4,
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
    fontSize: 12, fontWeight: 700,
  });

  return (
    <>
    {/* TODO(photos): פיצ'ר הוספת תמונות אחרי דוח הוסר ב-v3.9.0.41 — צריך לתכנן מחדש זרימת תמונות→Drive. */}
    <V1Shell
      active="projects"
      onNav={onNav || (() => {})}
      onBack={onBack}
      title={<span>סיכום פגישה חדש <span style={{ fontSize: 12, background: '#1a2c4a', color: '#fff', padding: '3px 8px', borderRadius: 4, fontWeight: 700, letterSpacing: 0.4, marginInlineStart: 8 }}>{reportId}</span></span>}
      subtitle={`${project.name} • ${project.client}`}
      actions={
        <>
          <button style={{ background: '#fff', border: '1px solid var(--v1-border)', color: 'var(--v1-ink)', padding: '8px 14px', borderRadius: 6, fontSize: 13, cursor: 'pointer', fontFamily: 'inherit' }}>שמור טיוטה</button>
          {onOpenRecorder && (
            <button onClick={onOpenRecorder}
              style={{ background:'#fff', border:'1px solid #e5e7eb', color:'#1a2c4a',
                padding:'8px 14px', borderRadius:7, fontSize:13, fontWeight:600,
                cursor:'pointer', fontFamily:'inherit', display:'flex',
                alignItems:'center', gap:6 }}>
              🎙 הקלט פגישה
            </button>
          )}
          <button onClick={handleSubmit} style={{ background: 'var(--v1-accent)', color: '#fff', border: 'none', padding: '8px 16px', borderRadius: 6, fontSize: 13, fontWeight: 600, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6, fontFamily: 'inherit' }}>
            <Icon name="check" size={14}/>
            אשר ושלח דוח
          </button>
        </>
      }
    >
      <div style={{ padding: '20px 28px', maxWidth: 1000, margin: '0 auto' }}>

        {/* Auto-filled banner */}
        <div style={{ background: 'linear-gradient(to left, #eff6ff, #fff)', border: '1px solid #bfdbfe', borderRadius: 10, padding: '12px 16px', marginBottom: 14, display: 'flex', alignItems: 'center', gap: 12 }}>
          <div style={{ background: '#1a2c4a', color: '#fff', width: 32, height: 32, borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <Icon name="bolt" size={16}/>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: '#1a2c4a' }}>נתוני פרויקט מולאו אוטומטית</div>
            <div style={{ fontSize: 12, color: '#3b5378', marginTop: 2 }}>שם פרויקט, לקוח, מיקום, מספר דוח ({reportId}) ורושם — מתוך פרטי הפרויקט</div>
          </div>
        </div>

        {/* Section 1: Meeting details */}
        <div style={card}>
          <h3 style={sectionTitle}>
            <span style={stepNum(1)}>1</span>
            פרטי הפגישה
          </h3>
          <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 120px', gap: 14 }}>
            <div>
              <label style={labelStyle}>כותרת פגישה</label>
              <input style={inputStyle} value={meta.title} onChange={e => setMeta({...meta, title: e.target.value})}/>
            </div>
            <div>
              <label style={labelStyle}>תאריך</label>
              <input type="date" style={inputStyle} value={meta.date} onChange={e => setMeta({...meta, date: e.target.value})}/>
            </div>
            <div>
              <label style={labelStyle}>שעה</label>
              <input type="time" style={inputStyle} value={meta.time} onChange={e => setMeta({...meta, time: e.target.value})}/>
            </div>
            <div>
              <label style={labelStyle}>משך (דק׳)</label>
              <input type="number" style={inputStyle} value={meta.duration} onChange={e => setMeta({...meta, duration: e.target.value})}/>
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginTop: 14 }}>
            <div>
              <label style={labelStyle}>מיקום (אוטומטי)</label>
              <input style={inputReadOnly} value={meta.location} readOnly/>
            </div>
            <div>
              <label style={labelStyle}>רושם (אוטומטי)</label>
              <input style={inputReadOnly} value={meta.author} readOnly/>
            </div>
          </div>
        </div>

        {/* Section 2: Attendees with dropdown + manual */}
        <div style={card}>
          <h3 style={sectionTitle}>
            <span style={stepNum(2)}>2</span>
            משתתפים
            <span style={{ marginRight: 'auto', fontSize: 12, color: 'var(--v1-ink-soft)', fontWeight: 500 }}>{attendees.length} אנשים</span>
          </h3>

          {/* Current attendees */}
          <div style={{ border: '1px solid var(--v1-border)', borderRadius: 8, overflow: 'hidden', marginBottom: 10 }}>
            <div style={{ display: 'grid', gridTemplateColumns: '40px 1.2fr 1fr 1.3fr 1.2fr 28px', gap: 10, padding: '8px 12px', background: '#fafbfc', fontSize: 11, fontWeight: 600, color: 'var(--v1-ink-soft)', textTransform: 'uppercase' }}>
              <div></div><div>שם</div><div>תפקיד</div><div>חברה</div><div>אימייל</div><div></div>
            </div>
            {attendees.map((a) => (
              <div key={a.id} style={{ display: 'grid', gridTemplateColumns: '40px 1.2fr 1fr 1.3fr 1.2fr 28px', gap: 10, padding: '8px 12px', alignItems: 'center', borderTop: '1px solid var(--v1-border)', fontSize: 12.5 }}>
                <Avatar name={a.name} size={26}/>
                <div style={{ fontWeight: 500, display: 'flex', alignItems: 'center', gap: 6 }}>
                  {a.name}
                  {a.type === 'manual' && <span style={{ fontSize: 9, background: '#fef3c7', color: '#b45309', padding: '1px 5px', borderRadius: 2, fontWeight: 700 }}>ידני</span>}
                </div>
                <div style={{ color: 'var(--v1-ink-soft)' }}>{a.role}</div>
                <div style={{ color: 'var(--v1-ink-soft)' }}>{a.company}</div>
                <div style={{ color: 'var(--v1-ink-soft)', fontSize: 11.5, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{a.email || '—'}</div>
                <button onClick={() => removeAttendee(a.id)} style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: '#dc2626', padding: 0 }}>
                  <Icon name="close" size={14}/>
                </button>
              </div>
            ))}
          </div>

          {/* Picker */}
          {!showPicker ? (
            <div style={{ display: 'flex', gap: 8 }}>
              <button onClick={() => { setShowPicker(true); setManualMode(false); }} style={{ flex: 1, background: '#fff', border: '1px dashed var(--v1-border)', color: 'var(--v1-accent)', padding: '10px 14px', borderRadius: 6, fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 6, justifyContent: 'center' }}>
                <Icon name="users" size={14}/>
                הוסף מאנשי הקשר של הפרויקט
              </button>
              <button onClick={() => { setShowPicker(true); setManualMode(true); }} style={{ flex: 1, background: '#fff', border: '1px dashed var(--v1-border)', color: 'var(--v1-ink)', padding: '10px 14px', borderRadius: 6, fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 6, justifyContent: 'center' }}>
                <Icon name="plus" size={14}/>
                הוסף ידנית
              </button>
            </div>
          ) : (
            <div style={{ background: '#f9fafb', border: '1px solid var(--v1-border)', borderRadius: 8, padding: 14 }}>
              <div style={{ display: 'flex', gap: 8, marginBottom: 12, borderBottom: '1px solid var(--v1-border)', paddingBottom: 10 }}>
                <button onClick={() => setManualMode(false)} style={{ background: !manualMode ? 'var(--v1-accent)' : '#fff', color: !manualMode ? '#fff' : 'var(--v1-ink)', border: '1px solid ' + (!manualMode ? 'var(--v1-accent)' : 'var(--v1-border)'), padding: '5px 12px', borderRadius: 5, fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}>מאנשי הקשר</button>
                <button onClick={() => setManualMode(true)} style={{ background: manualMode ? 'var(--v1-accent)' : '#fff', color: manualMode ? '#fff' : 'var(--v1-ink)', border: '1px solid ' + (manualMode ? 'var(--v1-accent)' : 'var(--v1-border)'), padding: '5px 12px', borderRadius: 5, fontSize: 12, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}>הוספה ידנית</button>
                <button onClick={() => setShowPicker(false)} style={{ marginRight: 'auto', background: 'transparent', border: 'none', color: 'var(--v1-ink-soft)', cursor: 'pointer', fontSize: 12 }}>ביטול ✕</button>
              </div>

              {!manualMode ? (
                available.length ? available.map(c => (
                  <div key={c.id} onClick={() => addFromContacts(c)} style={{ display: 'grid', gridTemplateColumns: '32px 1fr 1fr 1fr auto', gap: 10, padding: '8px 10px', alignItems: 'center', cursor: 'pointer', background: '#fff', borderRadius: 5, marginBottom: 5, border: '1px solid var(--v1-border)' }}
                    onMouseEnter={e => e.currentTarget.style.background = '#eff6ff'}
                    onMouseLeave={e => e.currentTarget.style.background = '#fff'}>
                    <Avatar name={c.name} size={26}/>
                    <div style={{ fontSize: 12.5, fontWeight: 500 }}>{c.name}</div>
                    <div style={{ fontSize: 12, color: 'var(--v1-ink-soft)' }}>{c.role}</div>
                    <div style={{ fontSize: 12, color: 'var(--v1-ink-soft)' }}>{c.company}</div>
                    <Icon name="plus" size={14} color="var(--v1-accent)"/>
                  </div>
                )) : <div style={{ textAlign: 'center', padding: 20, color: 'var(--v1-ink-soft)', fontSize: 12 }}>כל אנשי הקשר כבר במשתתפים</div>
              ) : (
                <div style={{ display: 'grid', gap: 10 }}>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                    <div><label style={labelStyle}>שם מלא *</label><input style={inputStyle} value={manualContact.name} onChange={e => setManualContact({...manualContact, name: e.target.value})}/></div>
                    <div><label style={labelStyle}>תפקיד</label><input style={inputStyle} value={manualContact.role} onChange={e => setManualContact({...manualContact, role: e.target.value})}/></div>
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10 }}>
                    <div><label style={labelStyle}>חברה</label><input style={inputStyle} value={manualContact.company} onChange={e => setManualContact({...manualContact, company: e.target.value})}/></div>
                    <div><label style={labelStyle}>אימייל</label><input type="email" style={inputStyle} value={manualContact.email} onChange={e => setManualContact({...manualContact, email: e.target.value})}/></div>
                    <div><label style={labelStyle}>טלפון</label><input style={inputStyle} value={manualContact.phone} onChange={e => setManualContact({...manualContact, phone: e.target.value})}/></div>
                  </div>
                  <button onClick={addManual} disabled={!manualContact.name} style={{ background: 'var(--v1-accent)', color: '#fff', border: 'none', padding: '8px 14px', borderRadius: 5, fontSize: 12.5, fontWeight: 600, cursor: manualContact.name ? 'pointer' : 'not-allowed', opacity: manualContact.name ? 1 : 0.5, fontFamily: 'inherit' }}>
                    הוסף משתתף
                  </button>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Section 3: Agenda + Discussion (condensed) */}
        <div style={card}>
          <h3 style={sectionTitle}>
            <span style={stepNum(3)}>3</span>
            סדר יום ועיקרי הדיון
          </h3>
          <div style={{ background: '#f9fafb', borderRadius: 6, padding: 12, marginBottom: 10 }}>
            {agenda.map((item, i) => (
              <div key={i} style={{ display: 'flex', gap: 10, alignItems: 'center', padding: '4px 0' }}>
                <span style={{ width: 20, height: 20, borderRadius: 10, background: '#fff', color: 'var(--v1-accent)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700, flexShrink: 0, border: '1px solid var(--v1-border)' }}>{i+1}</span>
                <span style={{ fontSize: 13, flex: 1 }}>{item}</span>
                <button onClick={() => setAgenda(agenda.filter((_,j) => j !== i))} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#9ca3af', fontSize: 16, padding: '0 4px', lineHeight: 1 }}>✕</button>
              </div>
            ))}
            {agenda.length === 0 && <div style={{ fontSize: 12, color: '#9ca3af', textAlign: 'center', padding: '8px 0' }}>לא נוספו נושאים לסדר היום</div>}
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <input
              style={{ ...inputStyle, flex: 1 }}
              placeholder="הוסף נושא לסדר היום..."
              value={agendaInput}
              onChange={e => setAgendaInput(e.target.value)}
              onKeyDown={e => { if (e.key === 'Enter' && agendaInput.trim()) { setAgenda([...agenda, agendaInput.trim()]); setAgendaInput(''); } }}
            />
            <button
              onClick={() => { if (agendaInput.trim()) { setAgenda([...agenda, agendaInput.trim()]); setAgendaInput(''); } }}
              style={{ background: 'var(--v1-accent)', color: '#fff', border: 'none', borderRadius: 6, padding: '0 14px', fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', flexShrink: 0 }}>
              + הוסף
            </button>
          </div>
          {discussion.map((d, i) => (
            <div key={i} style={{ marginBottom: 10 }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--v1-accent)', marginBottom: 3 }}>{d.topic}</div>
              <textarea defaultValue={d.notes} style={{ ...inputStyle, minHeight: 50, resize: 'vertical', lineHeight: 1.5, fontSize: 12.5 }}/>
            </div>
          ))}
        </div>

        {/* Section 4: Decisions */}
        <div style={card}>
          <h3 style={sectionTitle}>
            <span style={stepNum(4, '#10b981')}>4</span>
            החלטות
          </h3>
          {decisions.map((d, i) => (
            <div key={i} style={{ display: 'flex', gap: 10, alignItems: 'flex-start', padding: '8px 0', borderTop: i > 0 ? '1px solid var(--v1-border)' : 'none' }}>
              <Icon name="check" size={15} color="#10b981" strokeWidth={2.5}/>
              <div style={{ fontSize: 13, lineHeight: 1.5, flex: 1 }}>{d}</div>
              <button onClick={() => setDecisions(decisions.filter((_,j) => j !== i))} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#9ca3af', fontSize: 16, padding: '0 4px', lineHeight: 1, flexShrink: 0 }}>✕</button>
            </div>
          ))}
          {decisions.length === 0 && <div style={{ fontSize: 12, color: '#9ca3af', textAlign: 'center', padding: '8px 0' }}>לא נוספו החלטות עדיין</div>}
          <DecisionInput onAdd={d => setDecisions([...decisions, d])} inputStyle={inputStyle} />
        </div>

        {/* Section 5: Findings → tasks */}
        <div style={{ ...card, border: '2px solid #fed7aa', background: 'linear-gradient(to left, #fff7ed, #fff)' }}>
          <h3 style={sectionTitle}>
            <span style={stepNum(5, '#ea580c')}>5</span>
            ממצאים ורג׳קטים לטיפול
            <span style={{ marginRight: 'auto', fontSize: 12, background: '#1a2c4a', color: '#fff', padding: '3px 10px', borderRadius: 12, fontWeight: 600 }}>
              ⚡ הופכים אוטומטית למשימות — יעד 7 ימים
            </span>
          </h3>

          <div style={{ fontSize: 12, color: '#7c2d12', marginBottom: 14, background: '#fff7ed', padding: 10, borderRadius: 6, border: '1px solid #fed7aa' }}>
            💡 כל ממצא שתוסיף כאן יהפוך אוטומטית למשימה פעילה עם תג <b>{reportId}</b> • בשליחה ללקוח/קבלן, הם יוכלו לסמן בוצע, לשנות תאריך או להוסיף הערה — הכל מסתנכרן חזרה לאפליקציה.
          </div>

          {findings.map((f, i) => (
            <FindingEditor
              key={f.id}
              finding={f}
              index={i}
              contacts={contacts}
              onUpdate={(patch) => updateFinding(f.id, patch)}
              onRemove={() => removeFinding(f.id)}
              onPhoto={(file) => handlePhotoUpload(f.id, file)}
            />
          ))}

          <button onClick={addFinding} style={{ width: '100%', background: '#fff', border: '1px dashed #ea580c', color: '#ea580c', padding: '12px', borderRadius: 8, fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 6, justifyContent: 'center' }}>
            <Icon name="plus" size={14}/>
            הוסף ממצא חדש
          </button>
        </div>

        {/* Section 6: Next meeting with Google Calendar */}
        <div style={{ ...card, background: 'linear-gradient(to left, #eff6ff, #fff)', borderColor: '#bfdbfe' }}>
          <h3 style={sectionTitle}>
            <Icon name="calendar" size={18} color="var(--v1-accent)"/>
            תיאום פגישה הבאה
          </h3>
          <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 2fr', gap: 10, marginBottom: 12 }}>
            <div>
              <label style={labelStyle}>כותרת</label>
              <input style={inputStyle} value={nextMeeting.title} onChange={e => setNextMeeting({...nextMeeting, title: e.target.value})}/>
            </div>
            <div>
              <label style={labelStyle}>תאריך</label>
              <input type="date" style={inputStyle} value={nextMeeting.date} onChange={e => setNextMeeting({...nextMeeting, date: e.target.value})}/>
            </div>
            <div>
              <label style={labelStyle}>שעה</label>
              <input type="time" style={inputStyle} value={nextMeeting.time} onChange={e => setNextMeeting({...nextMeeting, time: e.target.value})}/>
            </div>
            <div>
              <label style={labelStyle}>מיקום</label>
              <input style={inputStyle} value={nextMeeting.location} onChange={e => setNextMeeting({...nextMeeting, location: e.target.value})}/>
            </div>
          </div>
          <button
            onClick={() => {
              const emails = contacts.map(c => c.email);
              const url = window.buildGCalUrl({
                ...nextMeeting,
                duration: 90,
                description: `פגישת תיאום לפרויקט: ${project.name}\nלקוח: ${project.client}\nמנהל פרויקט: ${meta.author}\n\nמסמך סיכום אחרון: ${reportId}`,
                attendees: emails,
              });
              window.open(url, '_blank');
              SyncStore.scheduleMeeting({
                ...nextMeeting,
                projectId,
                attendees: attendees.map(a => a.name),
                syncedToGCal: true,
              });
            }}
            style={{
              background: '#fff', border: '1px solid var(--v1-border)', color: 'var(--v1-ink)',
              padding: '10px 16px', borderRadius: 6, fontSize: 13, fontWeight: 600, cursor: 'pointer',
              fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 8, boxShadow: '0 1px 2px rgba(0,0,0,0.05)',
            }}
          >
            <svg width="16" height="16" viewBox="0 0 48 48"><path fill="#4285F4" d="M37 6H11a5 5 0 00-5 5v26a5 5 0 005 5h26a5 5 0 005-5V11a5 5 0 00-5-5z"/><path fill="#fff" d="M24 31a7 7 0 110-14 7 7 0 010 14zm0-12a5 5 0 100 10 5 5 0 000-10z"/><text x="24" y="14" fontSize="6" fill="#fff" textAnchor="middle" fontWeight="bold">{nextMeeting.date.slice(-2)}</text></svg>
            הוסף ל-Google Calendar (מסונכרן עם יומן שלך)
          </button>
        </div>

        {/* Send bar */}
        <div style={{ position: 'sticky', bottom: 0, background: '#1a2c4a', margin: '0 -28px -20px', padding: '14px 28px', display: 'flex', alignItems: 'center', gap: 12, boxShadow: '0 -4px 20px rgba(0,0,0,0.15)' }}>
          <div style={{ flex: 1, color: '#fff' }}>
            <div style={{ fontSize: 13, fontWeight: 700 }}>מוכן לשליחה?</div>
            <div style={{ fontSize: 11.5, opacity: 0.7 }}>
              {findings.filter(f => f.title).length} ממצאים → משימות • {attendees.length} משתתפים • ישלח ל-{contacts.length} אנשי קשר בפרויקט
            </div>
          </div>
          <button onClick={handleSubmit} style={{ background: 'transparent', border: '1px solid rgba(255,255,255,0.3)', color: '#fff', padding: '9px 18px', borderRadius: 6, fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}>
            אשר ויצור משימות
          </button>
          <button onClick={() => { handleSubmit(); setTimeout(handleSendEmail, 200); }} style={{ background: '#fff', color: '#1a2c4a', border: 'none', padding: '9px 18px', borderRadius: 6, fontSize: 13, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 6 }}>
            <Icon name="send" size={14}/>
            שלח (Gmail)
          </button>
        </div>

      </div>
    </V1Shell>
    </>
  );
};
// ============================================================
const FindingEditor = ({ finding, index, contacts, onUpdate, onRemove, onPhoto }) => {
  const fileRef = useRef(null);
  const sev = SEVERITY_STYLES[finding.severity] || SEVERITY_STYLES.medium;
  const inputStyle = {
    width: '100%', padding: '7px 10px', border: '1px solid #fed7aa',
    borderRadius: 5, fontSize: 12.5, fontFamily: 'inherit', background: '#fff',
    color: 'var(--v1-ink)', outline: 'none',
  };

  return (
    <div style={{ background: '#fff', border: '1px solid #fed7aa', borderRadius: 8, padding: 14, marginBottom: 10 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
        <span style={{ background: '#ea580c', color: '#fff', width: 26, height: 26, borderRadius: 13, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 700 }}>
          #{index + 1}
        </span>
        <span style={{ fontSize: 13, fontWeight: 700, flex: 1 }}>ממצא חדש</span>
        <span style={{ fontSize: 10.5, background: sev.bg, color: sev.fg, padding: '2px 8px', borderRadius: 3, fontWeight: 700 }}>חומרה: {sev.label}</span>
        <button onClick={onRemove} style={{ background: 'transparent', border: 'none', color: '#dc2626', cursor: 'pointer', padding: 4 }}>
          <Icon name="close" size={14}/>
        </button>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '120px 1fr', gap: 12 }}>
        {/* Photo area */}
        <div>
          {finding.photo ? (
            <div style={{ position: 'relative', borderRadius: 6, overflow: 'hidden', height: 120 }}>
              <img src={finding.photo} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }}/>
              <button onClick={() => onUpdate({ photo: null })} style={{ position: 'absolute', top: 4, left: 4, background: 'rgba(0,0,0,0.6)', color: '#fff', border: 'none', borderRadius: 3, padding: '2px 6px', fontSize: 10, cursor: 'pointer' }}>הסר ✕</button>
            </div>
          ) : (
            <PhotoPickerSheet onFiles={files => onPhoto(files[0])}>
              <div style={{ height: 120, border: '2px dashed #fed7aa', borderRadius: 6, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 4, cursor: 'pointer', background: '#fffbf5', color: '#ea580c' }}>
                <Icon name="camera" size={22}/>
                <span style={{ fontSize: 11, fontWeight: 600 }}>צלם / העלה</span>
                <span style={{ fontSize: 9.5, color: '#9a4f20' }}>תמונה מהטלפון</span>
              </div>
            </PhotoPickerSheet>
          )}
        </div>

        <div style={{ display: 'grid', gap: 8 }}>
          <input style={{ ...inputStyle, fontWeight: 600 }} placeholder="כותרת הממצא *" value={finding.title} onChange={e => onUpdate({ title: e.target.value })}/>
          <textarea style={{ ...inputStyle, minHeight: 40, resize: 'vertical' }} placeholder="תיאור מפורט של הממצא..." value={finding.description} onChange={e => onUpdate({ description: e.target.value })}/>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            <input style={inputStyle} placeholder="מיקום בשטח" value={finding.location} onChange={e => onUpdate({ location: e.target.value })}/>
            <select style={inputStyle} value={finding.assignee} onChange={e => onUpdate({ assignee: e.target.value })}>
              <option value="">אחראי לתיקון...</option>
              {contacts.map(c => <option key={c.id} value={c.name}>{c.name} — {c.role}</option>)}
            </select>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
            <select style={inputStyle} value={finding.severity} onChange={e => onUpdate({ severity: e.target.value })}>
              <option value="high">חומרה גבוהה — דחוף</option>
              <option value="medium">חומרה בינונית</option>
              <option value="low">חומרה נמוכה</option>
            </select>
            <input type="date" style={inputStyle} value={finding.due} onChange={e => onUpdate({ due: e.target.value })}/>
          </div>
        </div>
      </div>
    </div>
  );
};

// ============================================================
// Confirmation screen — shows what was created
// ============================================================
const MeetingSubmittedScreen = ({ reportId, projectId, onViewReport, onViewTasks, onBack }) => {
  const report = SyncStore.get().reports.find(r => r.id === reportId);
  const tasks = SyncStore.get().tasks.filter(t => t.sourceReportId === reportId && t.status !== 'archived');
  const project = YBP_DATA.projects.find(p => p.id === projectId);

  return (
    <V1Shell active="projects" onNav={() => {}} onBack={onBack} title="הדוח נשלח בהצלחה" subtitle={`${project.name} • ${reportId}`}>
      <div style={{ padding: '40px 28px', maxWidth: 700, margin: '0 auto' }}>
        <div style={{ background: '#fff', border: '1px solid var(--v1-border)', borderRadius: 12, padding: 32, textAlign: 'center', marginBottom: 20 }}>
          <div style={{ width: 64, height: 64, background: '#d1fae5', borderRadius: 32, margin: '0 auto 16px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name="check" size={32} color="#059669" strokeWidth={3}/>
          </div>
          <h2 style={{ margin: '0 0 6px', fontSize: 22, color: 'var(--v1-ink)' }}>הדוח נוצר ונשלח</h2>
          <div style={{ fontSize: 14, color: 'var(--v1-ink-soft)' }}>
            <span style={{ background: '#1a2c4a', color: '#fff', padding: '3px 10px', borderRadius: 4, fontFamily: 'ui-monospace, monospace', fontSize: 13, marginLeft: 6 }}>{reportId}</span>
            מופיע בארכיון הפרויקט
          </div>
        </div>

        <div style={{ background: '#fff', border: '1px solid var(--v1-border)', borderRadius: 12, padding: 20, marginBottom: 14 }}>
          <div style={{ fontSize: 13, fontWeight: 700, marginBottom: 12, display: 'flex', alignItems: 'center', gap: 8 }}>
            <Icon name="task" size={16} color="#ea580c"/>
            {tasks.length} משימות נוצרו אוטומטית מהממצאים
          </div>
          {tasks.map(t => (
            <div key={t.id} style={{ display: 'flex', gap: 10, alignItems: 'center', padding: '8px 0', borderTop: '1px solid var(--v1-border)' }}>
              <div style={{ width: 8, height: 8, borderRadius: 4, background: SEVERITY_STYLES[t.severity]?.dot || '#6b7280' }}/>
              <div style={{ flex: 1, fontSize: 12.5 }}>{t.title}</div>
              <span style={{ fontSize: 10, background: '#1a2c4a', color: '#fff', padding: '2px 6px', borderRadius: 3, fontFamily: 'ui-monospace, monospace' }}>{reportId}</span>
              <span style={{ fontSize: 11.5, color: 'var(--v1-ink-soft)' }}>יעד: {t.due}</span>
            </div>
          ))}
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <button onClick={onViewTasks} style={{ background: '#fff', border: '1px solid var(--v1-border)', color: 'var(--v1-ink)', padding: '12px 16px', borderRadius: 8, fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 8, justifyContent: 'center' }}>
            <Icon name="task" size={14}/>
            צפה במשימות שנוצרו
          </button>
          <button onClick={onViewReport} style={{ background: 'var(--v1-accent)', color: '#fff', border: 'none', padding: '12px 16px', borderRadius: 8, fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 8, justifyContent: 'center' }}>
            <Icon name="eye" size={14}/>
            פתח דוח אינטראקטיבי (תצוגת לקוח)
          </button>
        </div>
      </div>
    </V1Shell>
  );
};

Object.assign(window, { MeetingFormScreen, MeetingSubmittedScreen });
})();
