// Tasks panel + Meetings tab (Google Calendar mockup) + activity feed
(function(){
const { useState, useEffect } = React;

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

const TASK_STATUS = {
  'open':        { label: 'לביצוע', bg: '#f3f4f6', fg: '#4b5563' },
  'in-progress': { label: 'בביצוע', bg: '#dbeafe', fg: '#1d4ed8' },
  'review':      { label: 'בבדיקה', bg: '#fef3c7', fg: '#b45309' },
  'done':        { label: 'הושלם',  bg: '#d1fae5', fg: '#047857' },
};

// צבע אחיד לסטטוסים מותאמים
const CUSTOM_STATUS = { bg: '#e0e7ff', fg: '#4338ca' };

// תווית סטטוס לחיצה — שינוי סטטוס מיידי + הוספת סטטוס מותאם
const StatusBadge = ({ task }) => {
  const [open, setOpen] = useState(false);
  const ref = React.useRef();
  useEffect(() => {
    if (!open) return;
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', h);
    return () => document.removeEventListener('mousedown', h);
  }, [open]);

  const store = (typeof SyncStore !== 'undefined') ? SyncStore.get() : { tasks: [] };
  // סטטוסים מותאמים = ערכי status ייחודיים שאינם מובנים
  const customStatuses = Array.from(new Set(
    (store.tasks || []).map(t => t.status).filter(s => s && !TASK_STATUS[s])
  ));

  const cur = TASK_STATUS[task.status]
    || (task.status ? { label: task.status, ...CUSTOM_STATUS } : TASK_STATUS['open']);

  const pick = (value) => {
    if (typeof SyncStore !== 'undefined') SyncStore.updateTask(task.id, { status: value });
    setOpen(false);
  };
  const addNew = () => {
    const name = (window.prompt('שם הסטטוס החדש:') || '').trim();
    setOpen(false);
    if (name) pick(name);
  };

  const item = (active) => ({
    display: 'flex', alignItems: 'center', gap: 7, width: '100%',
    padding: '7px 11px', background: active ? '#f3f4f6' : '#fff', border: 'none',
    fontSize: 12, color: '#374151', cursor: 'pointer', fontFamily: 'inherit', textAlign: 'right',
  });

  return (
    <span ref={ref} style={{ position: 'relative', display: 'inline-block' }}>
      <button onClick={(e) => { e.stopPropagation(); setOpen(o => !o); }} style={{
        fontSize: 10, background: cur.bg, color: cur.fg, padding: '2px 8px',
        borderRadius: 3, fontWeight: 700, border: 'none', cursor: 'pointer',
        fontFamily: 'inherit', display: 'inline-flex', alignItems: 'center', gap: 4,
      }}>
        {cur.label} <span style={{ fontSize: 7, opacity: 0.7 }}>▼</span>
      </button>
      {open && (
        <div style={{
          position: 'absolute', top: '100%', right: 0, marginTop: 4, zIndex: 999,
          background: '#fff', border: '1px solid #e5e7eb', borderRadius: 7,
          boxShadow: '0 6px 20px rgba(0,0,0,0.14)', minWidth: 150, overflow: 'hidden',
        }}>
          {Object.keys(TASK_STATUS).map(k => (
            <button key={k} onClick={() => pick(k)} style={item(task.status === k)}>
              <span style={{ width: 9, height: 9, borderRadius: 5, background: TASK_STATUS[k].fg, flexShrink: 0 }}/>
              {TASK_STATUS[k].label}
            </button>
          ))}
          {customStatuses.map(s => (
            <button key={s} onClick={() => pick(s)} style={item(task.status === s)}>
              <span style={{ width: 9, height: 9, borderRadius: 5, background: CUSTOM_STATUS.fg, flexShrink: 0 }}/>
              {s}
            </button>
          ))}
          <button onClick={addNew} style={{ ...item(false), color: '#1d4ed8', fontWeight: 700, borderTop: '1px solid #e5e7eb' }}>
            ＋ סטטוס חדש
          </button>
        </div>
      )}
    </span>
  );
};

// ============================================================
// TASKS PANEL — shows all tasks (from findings + regular), sorted by status
// ============================================================
// ── Add Task Modal ────────────────────────────────────────────────────────────
const AddTaskModal = ({ projectId, onClose }) => {
  const contacts = YBP_DATA.projectDetail?.contacts || [];
  const [title, setTitle] = useState('');
  const [description, setDesc] = useState('');
  const [assignee, setAssignee] = useState('');
  const [due, setDue] = useState(() => { const d = new Date(); d.setDate(d.getDate()+7); return d.toISOString().slice(0,10); });
  const [severity, setSeverity] = useState('medium');

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

  const handleSubmit = () => {
    if (!title.trim()) return;
    SyncStore.addTask({ projectId, title: title.trim(), description, assignee, due, severity, source: 'pm' });
    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:12, width:'100%', maxWidth:480, boxShadow:'0 20px 60px rgba(0,0,0,0.25)', fontFamily:'Assistant,sans-serif', direction:'rtl' }}>
        <div style={{ padding:'16px 20px', borderBottom:'1px solid #e5e7eb', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
          <span style={{ fontSize:16, fontWeight:700, color:'#1f2937' }}>הוספת משימה חדשה</span>
          <button onClick={onClose} style={{ background:'none', border:'none', fontSize:20, cursor:'pointer', color:'#9ca3af' }}>✕</button>
        </div>
        <div style={{ padding:'20px', display:'flex', flexDirection:'column', gap:14 }}>
          <div>
            <label style={{ fontSize:12, fontWeight:700, color:'#374151', display:'block', marginBottom:5 }}>כותרת *</label>
            <input value={title} onChange={e => setTitle(e.target.value)} placeholder="תאר את המשימה..." style={inp} autoFocus/>
          </div>
          <div>
            <label style={{ fontSize:12, fontWeight:700, color:'#374151', display:'block', marginBottom:5 }}>תיאור</label>
            <textarea value={description} onChange={e => setDesc(e.target.value)} rows={2} placeholder="פרטים נוספים..." style={{ ...inp, resize:'vertical' }}/>
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
            <div>
              <label style={{ fontSize:12, fontWeight:700, color:'#374151', display:'block', marginBottom:5 }}>אחראי</label>
              <select value={assignee} onChange={e => setAssignee(e.target.value)} style={inp}>
                <option value="">— בחר —</option>
                {contacts.map(c => <option key={c.id} value={c.name}>{c.name}</option>)}
              </select>
            </div>
            <div>
              <label style={{ fontSize:12, fontWeight:700, color:'#374151', display:'block', marginBottom:5 }}>תאריך יעד</label>
              <input type="date" value={due} onChange={e => setDue(e.target.value)} style={inp}/>
            </div>
          </div>
          <div>
            <label style={{ fontSize:12, fontWeight:700, color:'#374151', display:'block', marginBottom:5 }}>עדיפות</label>
            <div style={{ display:'flex', gap:8 }}>
              {[['high','גבוהה','#fee2e2','#991b1b'],['medium','בינונית','#fef3c7','#b45309'],['low','נמוכה','#dbeafe','#1e40af']].map(([k,label,bg,fg]) => (
                <button key={k} onClick={() => setSeverity(k)} style={{
                  flex:1, padding:'8px', borderRadius:6, fontSize:12, fontWeight:700, cursor:'pointer', fontFamily:'inherit',
                  border: severity===k ? `2px solid ${fg}` : '2px solid #e5e7eb',
                  background: severity===k ? bg : '#fff', color: severity===k ? fg : '#9ca3af',
                }}>{label}</button>
              ))}
            </div>
          </div>
        </div>
        <div style={{ padding:'14px 20px', borderTop:'1px solid #e5e7eb', display:'flex', gap:10 }}>
          <button onClick={handleSubmit} disabled={!title.trim()} style={{
            flex:1, padding:'10px', borderRadius:6, border:'none', fontFamily:'inherit',
            background: title.trim() ? '#1a2c4a' : '#e5e7eb', color: title.trim() ? '#fff' : '#9ca3af',
            fontWeight:700, fontSize:14, cursor: title.trim() ? 'pointer' : 'not-allowed',
          }}>הוסף משימה</button>
          <button onClick={onClose} style={{ padding:'10px 16px', borderRadius:6, border:'1px solid #e5e7eb', background:'#fff', color:'#6b7280', fontSize:14, cursor:'pointer', fontFamily:'inherit' }}>ביטול</button>
        </div>
      </div>
    </div>
  );
};

const ProjectTasksScreen = ({ projectId, onBack, onOpenReport }) => {
  const [store, setStore] = useState(SyncStore.get());
  useEffect(() => SyncStore.subscribe(setStore), []);
  const { isMobile } = useViewport();
  const [showAddModal, setShowAddModal] = useState(false);
  const [collapsed, setCollapsed] = useState(false);

  const project = projectId ? YBP_DATA.projects.find(p => p.id === projectId) : null;
  const isAllProjects = !projectId;
  const allTasks = (isAllProjects ? (store.tasks || []) : store.tasks.filter(t => t.projectId === projectId))
    .filter(t => t.status !== 'archived');

  const [filter, setFilter] = useState('all'); // all | open | done | reject | pm
  const filtered = allTasks.filter(t => {
    if (filter === 'open') return t.status !== 'done';
    if (filter === 'done') return t.status === 'done';
    if (filter === 'reject') return t.source === 'reject' || t.source === 'finding';
    if (filter === 'pm') return t.source === 'pm';
    return true;
  });

  const openCount = allTasks.filter(t => t.status !== 'done').length;
  const doneCount = allTasks.filter(t => t.status === 'done').length;
  const rejectCount = allTasks.filter(t => t.source === 'reject' || t.source === 'finding').length;

  // Recent activity
  const activity = store.activity.slice(-8).reverse();

  return (
    <div style={{ minHeight: '100%', background: 'var(--v1-bg,#f6f7f9)', fontFamily: 'Assistant, sans-serif', direction: 'rtl' }}>
      {/* Header */}
      <div style={{ background: '#fff', borderBottom: '1px solid var(--v1-border,#e5e7eb)', padding: '14px 28px', display: 'flex', alignItems: 'center', gap: 12 }}>
        <button onClick={onBack} style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: '#6b7280', display: 'flex', alignItems: 'center', gap: 4, fontSize: 14, padding: 6, fontFamily: 'inherit' }}>
          ← חזרה
        </button>
        <div style={{ width: 1, height: 24, background: 'var(--v1-border,#e5e7eb)' }}/>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 11, color: '#6b7280', fontWeight: 600, letterSpacing: 0.3 }}>{project?.name ?? 'כל הפרויקטים'}</div>
          <div style={{ fontSize: 17, fontWeight: 700, color: '#1f2937' }}>{isAllProjects ? 'כל המשימות' : 'משימות הפרויקט'}</div>
        </div>
        {!isAllProjects && (
          <button onClick={() => setShowAddModal(true)} style={{
            background: '#1a2c4a', color: '#fff', border: 'none',
            padding: '8px 14px', borderRadius: 6, fontSize: 13, fontWeight: 600,
            cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6, fontFamily: 'inherit',
          }}>
            <Icon name="plus" size={14}/>
            הוסף משימה
          </button>
        )}
      </div>
      {showAddModal && <AddTaskModal projectId={projectId} onClose={() => setShowAddModal(false)}/>}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 300px', gap: 20, padding: '20px 28px', maxWidth: 1200, margin: '0 auto' }}>

        {/* Main tasks list */}
        <div>
          {/* Filter tabs */}
          <div style={{ display: 'flex', gap: 6, marginBottom: 16, alignItems: 'center', flexWrap: 'wrap' }}>
            {[
              ['all', `הכל (${allTasks.length})`],
              ['open', `פתוחות (${openCount})`],
              ['done', `בוצעו (${doneCount})`],
              ['reject', `ריג׳קטים (${rejectCount})`],
            ].map(([k, label]) => (
              <button key={k} onClick={() => setFilter(k)} style={{
                background: filter === k ? '#1a2c4a' : '#fff',
                color: filter === k ? '#fff' : 'var(--v1-ink)',
                border: '1px solid ' + (filter === k ? '#1a2c4a' : 'var(--v1-border)'),
                padding: '7px 14px', borderRadius: 6, fontSize: 12.5, fontWeight: 600,
                cursor: 'pointer', fontFamily: 'inherit',
              }}>{label}</button>
            ))}
            <button onClick={() => setCollapsed(c => !c)} style={{
              marginRight: 'auto', background: '#fff', color: 'var(--v1-ink)',
              border: '1px solid var(--v1-border)', padding: '7px 12px', borderRadius: 6,
              fontSize: 12.5, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
              display: 'flex', alignItems: 'center', gap: 5,
            }}>{collapsed ? '⌄ הרחב הכל' : '⌃ כווץ הכל'}</button>
          </div>

          {/* Task cards */}
          {isAllProjects ? (
            (() => {
              const groups = {};
              filtered.forEach(t => {
                const pId = t.projectId || '__no_project__';
                if (!groups[pId]) groups[pId] = [];
                groups[pId].push(t);
              });
              return Object.entries(groups).map(([pId, tasks]) => {
                const proj = pId === '__no_project__' ? null : YBP_DATA.projects.find(p => p.id === pId);
                return (
                  <div key={pId} style={{ marginBottom: 18 }}>
                    <div style={{ fontSize: 13, fontWeight: 700, color: '#1a2c4a', marginBottom: 8, display: 'flex', alignItems: 'center', gap: 8, padding: '6px 0', borderBottom: '2px solid #e5e7eb' }}>
                      <span>📁 {proj?.name ?? 'ללא פרויקט'}</span>
                      <span style={{ background: '#e5e7eb', color: '#6b7280', padding: '1px 8px', borderRadius: 10, fontSize: 11 }}>{tasks.length}</span>
                    </div>
                    {tasks.map(task => <TaskCard key={task.id} task={task} store={store} onOpenReport={onOpenReport} showProjectBadge={true} collapsed={collapsed}/>)}
                  </div>
                );
              });
            })()
          ) : (
            filtered.map(task => <TaskCard key={task.id} task={task} store={store} onOpenReport={onOpenReport} collapsed={collapsed}/>)
          )}

          {filtered.length === 0 && (
            <div style={{ background: '#fff', border: '1px solid var(--v1-border)', borderRadius: 10, padding: 40, textAlign: 'center', color: 'var(--v1-ink-soft)' }}>
              אין משימות בקטגוריה זו
            </div>
          )}
        </div>

        {/* Sidebar: activity feed */}
        <div>
          <div style={{ background: '#fff', border: '1px solid var(--v1-border)', borderRadius: 10, overflow: 'hidden', position: 'sticky', top: 20 }}>
            <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--v1-border)', background: '#fafbfc', fontSize: 12.5, fontWeight: 700, color: '#1a2c4a', display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ width: 8, height: 8, background: '#10b981', borderRadius: 4 }}/>
              פעילות מדוחות אינטראקטיביים
            </div>
            {activity.length === 0 ? (
              <div style={{ padding: 20, fontSize: 12, color: 'var(--v1-ink-soft)', textAlign: 'center' }}>
                אין פעילות לאחרונה.<br/>
                <span style={{ fontSize: 11, opacity: 0.7 }}>כאן יופיעו פעולות של לקוחות וקבלנים על דוחות ששלחת.</span>
              </div>
            ) : (
              activity.map(a => {
                const task = store.tasks.find(t => t.id === a.taskId);
                const at = new Date(a.at);
                const emoji = a.type === 'complete' ? '✅' : a.type === 'postpone' ? '📅' : '💬';
                return (
                  <div key={a.id} style={{ padding: '10px 16px', borderTop: '1px solid var(--v1-border)', fontSize: 12 }}>
                    <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 3 }}>
                      <span style={{ fontSize: 14 }}>{emoji}</span>
                      <b style={{ fontSize: 11.5 }}>{a.actor}</b>
                      <span style={{ marginRight: 'auto', fontSize: 10, color: 'var(--v1-ink-soft)' }}>{at.toLocaleTimeString('he-IL', { hour: '2-digit', minute: '2-digit' })}</span>
                    </div>
                    <div style={{ fontSize: 11.5, color: 'var(--v1-ink-soft)', paddingRight: 22, lineHeight: 1.4 }}>
                      {a.type === 'complete' && <>סימן כבוצע: <b>{task?.title}</b></>}
                      {a.type === 'postpone' && <>דחה תאריך: <b>{task?.title}</b> ל-{a.details.newDue}</>}
                      {a.type === 'comment' && <>הוסיף הערה: "<i>{a.details.text}</i>"</>}
                    </div>
                    {a.reportId && <div style={{ marginTop: 4, paddingRight: 22 }}><span style={{ fontSize: 9.5, background: '#1a2c4a', color: '#fff', padding: '1px 6px', borderRadius: 3, fontFamily: 'ui-monospace, monospace', fontWeight: 700 }}>{a.reportId}</span></div>}
                  </div>
                );
              })
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

const TaskCard = ({ task, store, onOpenReport, showProjectBadge, collapsed }) => {
  const project = showProjectBadge ? YBP_DATA.projects.find(p => p.id === task.projectId) : null;
  const sev = SEVERITY[task.severity] || SEVERITY.medium;
  const isDone = task.status === 'done';
  const comments = task.comments || [];
  const [editing, setEditing] = useState(false);
  const [draft, setDraft] = useState({});
  const [newComment, setNewComment] = useState('');
  const [expandedOverride, setExpandedOverride] = useState(false);
  useEffect(() => { setExpandedOverride(false); }, [collapsed]);

  const contacts = YBP_DATA.projectDetail?.contacts || [];

  const startEdit = () => {
    setDraft({
      title: task.title,
      description: task.description || '',
      assignee: task.assignee || '',
      due: task.due || '',
      severity: task.severity || 'medium',
    });
    setEditing(true);
  };

  const saveEdit = () => {
    SyncStore.updateTask(task.id, draft);
    setEditing(false);
  };

  const toggleDone = () => {
    SyncStore.updateTask(task.id, {
      status: isDone ? 'open' : 'done',
      completedAt: isDone ? null : new Date().toISOString(),
      completedBy: isDone ? null : YBP_DATA.user.name,
    });
  };

  const deleteTask = () => {
    if (confirm(`למחוק "${task.title}"?`)) SyncStore.deleteTask(task.id);
  };

  const addComment = () => {
    if (!newComment.trim()) return;
    SyncStore.addComment(task.id, { author: YBP_DATA.user.name, text: newComment.trim(), at: new Date().toISOString() });
    setNewComment('');
  };

  const inp = { width: '100%', padding: '6px 8px', border: '1px solid #e5e7eb', borderRadius: 5, fontSize: 12.5, fontFamily: 'inherit', background: '#fff', boxSizing: 'border-box' };

  // ── תצוגה מכווצת — שורה אחת קומפקטית, לחיצה מרחיבה את הכרטיס ──
  if (collapsed && !expandedOverride && !editing) {
    return (
      <div style={{
        background: '#fff', border: '1px solid var(--v1-border)',
        borderRight: `4px solid ${isDone ? '#10b981' : sev.dot}`,
        borderRadius: 8, padding: '8px 12px', marginBottom: 6,
        display: 'flex', alignItems: 'center', gap: 10,
      }}>
        <div onClick={toggleDone} style={{
          width: 18, height: 18, borderRadius: 9, flexShrink: 0, cursor: 'pointer',
          border: '2px solid ' + (isDone ? '#10b981' : '#d1d5db'),
          background: isDone ? '#10b981' : 'transparent',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          {isDone && <Icon name="check" size={9} color="#fff" strokeWidth={4}/>}
        </div>
        <div onClick={() => setExpandedOverride(true)} style={{ flex: 1, minWidth: 0, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{ fontSize: 13, fontWeight: 600, color: isDone ? 'var(--v1-ink-soft)' : 'var(--v1-ink)', textDecoration: isDone ? 'line-through' : 'none', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{task.title}</span>
          {task.due && <span style={{ fontSize: 10.5, color: 'var(--v1-ink-soft)', flexShrink: 0 }}>📅 {task.due}</span>}
        </div>
        {showProjectBadge && project && <span style={{ fontSize: 10, color: 'var(--v1-ink-soft)', flexShrink: 0 }}>📁 {project.name}</span>}
        <StatusBadge task={task}/>
      </div>
    );
  }

  return (
    <div style={{
      background: '#fff', border: '1px solid var(--v1-border)',
      borderRight: `4px solid ${isDone ? '#10b981' : sev.dot}`,
      borderRadius: 8, padding: 14, marginBottom: 10,
      boxShadow: editing ? '0 4px 16px rgba(0,0,0,0.08)' : 'none',
    }}>
      {editing ? (
        // ===== EDIT MODE =====
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
            <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--v1-ink)' }}>עריכת משימה</div>
            <div style={{ marginRight: 'auto', display: 'flex', gap: 6 }}>
              <button onClick={() => setEditing(false)} style={{ padding: '5px 10px', borderRadius: 5, border: '1px solid #e5e7eb', background: '#fff', fontSize: 12, cursor: 'pointer', fontFamily: 'inherit' }}>ביטול</button>
              <button onClick={saveEdit} style={{ padding: '5px 12px', borderRadius: 5, border: 'none', background: '#1a2c4a', color: '#fff', fontSize: 12, fontWeight: 700, cursor: 'pointer', fontFamily: 'inherit' }}>שמור</button>
            </div>
          </div>
          <input value={draft.title} onChange={e => setDraft({...draft, title: e.target.value})} placeholder="כותרת" style={{ ...inp, fontWeight: 600, fontSize: 14 }}/>
          <textarea value={draft.description} onChange={e => setDraft({...draft, description: e.target.value})} placeholder="תיאור" rows={2} style={{ ...inp, resize: 'vertical' }}/>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
            <div>
              <label style={{ fontSize: 10.5, color: '#6b7280', fontWeight: 600, display: 'block', marginBottom: 3 }}>אחראי</label>
              <select value={draft.assignee} onChange={e => setDraft({...draft, assignee: e.target.value})} style={{ ...inp, marginBottom: 4 }}>
                <option value="">— בחר מרשימה —</option>
                {contacts.map(c => <option key={c.id} value={c.name}>{c.name}</option>)}
              </select>
              <input value={draft.assignee} onChange={e => setDraft({...draft, assignee: e.target.value})}
                placeholder="או הקלד ידנית..." style={{ ...inp, fontSize: 12 }}/>
            </div>
            <div>
              <label style={{ fontSize: 10.5, color: '#6b7280', fontWeight: 600, display: 'block', marginBottom: 3 }}>תאריך פתיחה</label>
              <input value={task.createdAt ? task.createdAt.slice(0,10) : task.due || ''} readOnly
                style={{ ...inp, background: '#f9fafb', color: '#9ca3af', cursor: 'not-allowed' }}/>
            </div>
            <div>
              <label style={{ fontSize: 10.5, color: '#6b7280', fontWeight: 600, display: 'block', marginBottom: 3 }}>תאריך יעד</label>
              <input type="date" value={draft.due} onChange={e => setDraft({...draft, due: e.target.value})} style={inp}/>
            </div>
            <div>
              <label style={{ fontSize: 10.5, color: '#6b7280', fontWeight: 600, display: 'block', marginBottom: 3 }}>סטטוס</label>
              <StatusBadge task={task}/>
            </div>
          </div>
          <div>
            <label style={{ fontSize: 10.5, color: '#6b7280', fontWeight: 600, display: 'block', marginBottom: 3 }}>חומרה</label>
            <div style={{ display: 'flex', gap: 6 }}>
              {['high','medium','low'].map(s => {
                const sv = SEVERITY[s];
                return (
                  <button key={s} onClick={() => setDraft({...draft, severity: s})} style={{
                    flex: 1, padding: '5px 8px', borderRadius: 5, fontSize: 12, fontWeight: 600,
                    border: draft.severity === s ? `1px solid ${sv.dot}` : '1px solid #e5e7eb',
                    background: draft.severity === s ? sv.bg : '#fff',
                    color: draft.severity === s ? sv.fg : '#6b7280',
                    cursor: 'pointer', fontFamily: 'inherit',
                  }}>{sv.label}</button>
                );
              })}
            </div>
          </div>
          <button onClick={deleteTask} style={{ alignSelf: 'flex-start', padding: '4px 10px', borderRadius: 5, border: '1px solid #fee2e2', background: '#fff', color: '#dc2626', fontSize: 11.5, cursor: 'pointer', fontFamily: 'inherit' }}>
            🗑 מחק משימה
          </button>
        </div>
      ) : (
        // ===== VIEW MODE =====
        <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
          <div onClick={toggleDone} style={{
            width: 20, height: 20, borderRadius: 10, flexShrink: 0, marginTop: 2, cursor: 'pointer',
            border: '2px solid ' + (isDone ? '#10b981' : '#d1d5db'),
            background: isDone ? '#10b981' : 'transparent',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            {isDone && <Icon name="check" size={10} color="#fff" strokeWidth={4}/>}
          </div>
          {task.photo && <img src={task.photo} style={{ width: 50, height: 50, borderRadius: 5, objectFit: 'cover', flexShrink: 0 }}/>}
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 3, flexWrap: 'wrap' }}>
              <div style={{ fontSize: 13.5, fontWeight: 600, color: isDone ? 'var(--v1-ink-soft)' : 'var(--v1-ink)', textDecoration: isDone ? 'line-through' : 'none' }}>{task.title}</div>
              <StatusBadge task={task}/>
              {project && <span style={{ fontSize: 10, background: '#dbeafe', color: '#1e40af', padding: '2px 7px', borderRadius: 3, fontWeight: 700 }}>📁 {project.name}</span>}
              <span style={{ fontSize: 10, background: sev.bg, color: sev.fg, padding: '2px 7px', borderRadius: 3, fontWeight: 700 }}>חומרה {sev.label}</span>
              {task.sourceReportId && <span onClick={() => onOpenReport?.(task.sourceReportId)} style={{ fontSize: 10, background: '#1a2c4a', color: '#fff', padding: '2px 7px', borderRadius: 3, fontWeight: 700, fontFamily: 'ui-monospace, monospace', cursor: 'pointer' }}>🔗 {task.sourceReportId}</span>}
              {task.postponed && <span style={{ fontSize: 10, background: '#fef3c7', color: '#b45309', padding: '2px 6px', borderRadius: 3 }}>נדחה</span>}
              <div style={{ marginRight: 'auto', display: 'flex', gap: 6 }}>
                <button onClick={startEdit} style={{ padding: '2px 8px', borderRadius: 4, border: '1px solid #e5e7eb', background: '#fff', color: '#6b7280', fontSize: 11, cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 3 }}>
                  <Icon name="edit" size={11}/> עריכה
                </button>
                <button onClick={deleteTask} style={{ padding: '2px 8px', borderRadius: 4, border: '1px solid #fee2e2', background: '#fff', color: '#dc2626', fontSize: 11, cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 3 }}>
                  🗑 מחק
                </button>
              </div>
            </div>
            {task.description && <div style={{ fontSize: 12, color: 'var(--v1-ink-soft)', marginBottom: 5 }}>{task.description}</div>}
            <div style={{ display: 'flex', gap: 14, fontSize: 11, color: 'var(--v1-ink-soft)', flexWrap: 'wrap', alignItems: 'center' }}>
              {task.location && <span>📍 {task.location}</span>}
              {task.assignee && <span style={{ display: 'flex', alignItems: 'center', gap: 4 }}><Avatar name={task.assignee} size={16}/> {task.assignee}</span>}
              {task.due && <span style={{ fontWeight: 600 }}>📅 {task.due}</span>}
              {isDone && task.completedBy && <span style={{ color: '#065f46' }}>✓ {task.completedBy}</span>}
            </div>
            {comments.length > 0 && (
              <div style={{ marginTop: 8, background: '#f9fafb', borderRadius: 5, padding: 8, fontSize: 11 }}>
                {comments.map((c, i) => <div key={i} style={{ padding: '2px 0' }}>💬 <b>{c.author}:</b> <span style={{ color: 'var(--v1-ink-soft)' }}>{c.text}</span></div>)}
              </div>
            )}
            {/* Add comment + WhatsApp */}
            <div style={{ display: 'flex', gap: 6, marginTop: 8 }}>
              <input value={newComment} onChange={e => setNewComment(e.target.value)} placeholder="הוסף הערה פנימית..."
                onKeyDown={e => e.key === 'Enter' && addComment()}
                style={{ flex: 1, padding: '5px 8px', border: '1px solid #e5e7eb', borderRadius: 5, fontSize: 12, fontFamily: 'inherit' }}/>
              <button onClick={addComment} disabled={!newComment.trim()} style={{ padding: '5px 10px', borderRadius: 5, border: 'none', background: '#1a2c4a', color: '#fff', fontSize: 11, cursor: 'pointer', fontFamily: 'inherit', opacity: newComment.trim() ? 1 : 0.4 }}>שמור</button>
              <button onClick={() => {
                const msg = `*${task.title}*\n${task.description || ''}\nאחראי: ${task.assignee || '—'}\nיעד: ${task.due || '—'}\n${newComment ? 'הערה: ' + newComment : ''}`;
                window.open(`https://wa.me/?text=${encodeURIComponent(msg)}`, '_blank');
              }} style={{ padding: '5px 10px', borderRadius: 5, border: 'none', background: '#25d366', color: '#fff', fontSize: 11, cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 4 }}>
                <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347z"/><path d="M12 2C6.477 2 2 6.477 2 12c0 1.89.525 3.66 1.438 5.168L2 22l4.832-1.438A9.96 9.96 0 0012 22c5.523 0 10-4.477 10-10S17.523 2 12 2z"/></svg>
                WhatsApp
              </button>
              <button onClick={() => {
                const contacts = YBP_DATA.projectDetail?.contacts || [];
                const assigneeContact = contacts.find(c => c.name === task.assignee);
                const to = assigneeContact?.email ? [assigneeContact.email] : [];
                const subject = `משימה: ${task.title}`;
                const body = `שלום,\n\nמשימה: ${task.title}\n${task.description ? 'תיאור: ' + task.description + '\n' : ''}אחראי: ${task.assignee || '—'}\nתאריך יעד: ${task.due || '—'}\n${newComment ? '\nהערה: ' + newComment : ''}\n\nYBPROJECTS`;
                const url = buildGmailUrl({ to, subject, body });
                window.open(url, '_blank');
              }} style={{ padding: '5px 10px', borderRadius: 5, border: 'none', background: '#ea4335', color: '#fff', fontSize: 11, cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 4 }}>
                <Icon name="send" size={12}/>
                Gmail
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// ============================================================
// MEETINGS TAB — Google Calendar embed mockup
// ============================================================
const ProjectMeetingsScreen = ({ projectId, onBack, onOpenReport, onNewMeeting, onOpenMeetingRecorder }) => {
  const [store, setStore] = useState(SyncStore.get());
  useEffect(() => SyncStore.subscribe(setStore), []);

  const project = YBP_DATA.projects.find(p => p.id === projectId);
  const storedMeetings = store.meetings.filter(m => m.projectId === projectId);
  const baseMeetings = YBP_DATA.projectDetail.meetings || [];
  const allMeetings = [...baseMeetings, ...storedMeetings];

  return (
    <div style={{ minHeight: '100%', background: 'var(--v1-bg,#f6f7f9)', fontFamily: 'Assistant, sans-serif', direction: 'rtl' }}>
      {/* Header */}
      <div style={{ background: '#fff', borderBottom: '1px solid var(--v1-border,#e5e7eb)', padding: '14px 28px', display: 'flex', alignItems: 'center', gap: 12 }}>
        <button onClick={onBack} style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: '#6b7280', display: 'flex', alignItems: 'center', gap: 4, fontSize: 14, padding: 6, fontFamily: 'inherit' }}>
          ← חזרה
        </button>
        <div style={{ width: 1, height: 24, background: 'var(--v1-border,#e5e7eb)' }}/>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 11, color: '#6b7280', fontWeight: 600, letterSpacing: 0.3 }}>{project.name}</div>
          <div style={{ fontSize: 17, fontWeight: 700, color: '#1f2937' }}>פגישות ולו״ז</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          {onOpenMeetingRecorder && (
            <button onClick={onOpenMeetingRecorder} style={{ background: '#dc2626', color: '#fff', border: 'none', padding: '8px 14px', borderRadius: 6, fontSize: 13, fontWeight: 600, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6, fontFamily: 'inherit' }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><line x1="12" y1="19" x2="12" y2="23"/><line x1="8" y1="23" x2="16" y2="23"/></svg>
              הקלט פגישה
            </button>
          )}
          <button onClick={onNewMeeting} style={{ background: 'var(--v1-accent,#1d4ed8)', color: '#fff', border: 'none', padding: '8px 14px', borderRadius: 6, fontSize: 13, fontWeight: 600, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6, fontFamily: 'inherit' }}>
            <Icon name="plus" size={14}/>
            תאם פגישה חדשה
          </button>
        </div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 380px', gap: 20, padding: '20px 28px', maxWidth: 1400, margin: '0 auto' }}>

        {/* Google Calendar mockup */}
        <GoogleCalendarMockup meetings={allMeetings} projectName={project.name} onOpenReport={onOpenReport}/>

        {/* Upcoming meetings list */}
        <div>
          <div style={{ background: '#fff', border: '1px solid var(--v1-border)', borderRadius: 10, overflow: 'hidden', marginBottom: 16 }}>
            <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--v1-border)', background: '#fafbfc', fontSize: 12.5, fontWeight: 700, display: 'flex', alignItems: 'center', gap: 8 }}>
              <Icon name="calendar" size={14} color="#1a2c4a"/>
              פגישות קרובות
            </div>
            {allMeetings.filter(m => m.status !== 'past').map(m => (
              <div key={m.id} style={{ padding: '12px 16px', borderTop: '1px solid var(--v1-border)' }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                  <div style={{ width: 4, height: 30, background: m.status === 'today' ? '#dc2626' : 'var(--v1-accent)', borderRadius: 2 }}/>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 12.5, fontWeight: 600 }}>{m.title}</div>
                    <div style={{ fontSize: 11, color: 'var(--v1-ink-soft)' }}>{m.date} · {m.time} · {m.duration || 60}ד׳</div>
                  </div>
                  {m.status === 'today' && <span style={{ fontSize: 10, background: '#fee2e2', color: '#991b1b', padding: '2px 6px', borderRadius: 3, fontWeight: 700 }}>היום</span>}
                </div>
                <div style={{ fontSize: 11, color: 'var(--v1-ink-soft)', marginRight: 12, display: 'flex', gap: 8, alignItems: 'center' }}>
                  📍 {m.location}
                  <span>·</span>
                  👥 {m.attendees} משתתפים
                </div>
              </div>
            ))}
          </div>

          {/* Past meetings with reports */}
          <div style={{ background: '#fff', border: '1px solid var(--v1-border)', borderRadius: 10, overflow: 'hidden' }}>
            <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--v1-border)', background: '#fafbfc', fontSize: 12.5, fontWeight: 700 }}>
              היסטוריית פגישות + סיכומים
            </div>
            {allMeetings.filter(m => m.status === 'past').map(m => (
              <div key={m.id} style={{ padding: '12px 16px', borderTop: '1px solid var(--v1-border)', display: 'flex', alignItems: 'center', gap: 10 }}>
                <Icon name="check" size={14} color="#10b981"/>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 600 }}>{m.title}</div>
                  <div style={{ fontSize: 11, color: 'var(--v1-ink-soft)' }}>{m.date}</div>
                </div>
                {m.reportId && (
                  <button onClick={() => onOpenReport?.(m.reportId)} style={{ background: '#1a2c4a', color: '#fff', border: 'none', padding: '4px 10px', borderRadius: 4, fontSize: 10.5, cursor: 'pointer', fontFamily: 'ui-monospace, monospace', fontWeight: 700 }}>
                    {m.reportId}
                  </button>
                )}
              </div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
};

// ============================================================
// Google Calendar embed mockup (week view)
// ============================================================
const GoogleCalendarMockup = ({ meetings, projectName, onOpenReport }) => {
  // Fixed week: April 13-19, 2026 (Mon-Sun)
  const weekDays = [
    { date: '2026-04-13', label: 'ב׳', num: 13 },
    { date: '2026-04-14', label: 'ג׳', num: 14 },
    { date: '2026-04-15', label: 'ד׳', num: 15 },
    { date: '2026-04-16', label: 'ה׳', num: 16 },
    { date: '2026-04-17', label: 'ו׳', num: 17 },
    { date: '2026-04-18', label: 'ש׳', num: 18, today: true },
    { date: '2026-04-19', label: 'א׳', num: 19 },
  ];
  const hours = ['08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00'];

  const otherEvents = [];

  const projectEvents = meetings
    .filter(m => weekDays.find(d => d.date === m.date))
    .map(m => ({
      day: m.date, time: m.time, duration: m.duration || 60,
      title: `📐 ${m.title}`, color: '#d50000', isProject: true, meeting: m,
    }));

  const allEvents = [...otherEvents, ...projectEvents];

  const timeToOffset = (time) => {
    const [h, mn] = time.split(':').map(Number);
    return (h - 8) * 60 + mn;
  };

  return (
    <div style={{ background: '#fff', border: '1px solid var(--v1-border)', borderRadius: 10, overflow: 'hidden' }}>
      {/* Calendar header (mimics Google Calendar chrome) */}
      <div style={{ background: '#fff', borderBottom: '1px solid #dadce0', padding: '10px 16px', display: 'flex', alignItems: 'center', gap: 12 }}>
        <svg width="24" height="24" viewBox="0 0 48 48">
          <rect x="6" y="8" width="36" height="34" rx="3" fill="#fff" stroke="#dadce0"/>
          <rect x="6" y="8" width="36" height="8" fill="#4285F4"/>
          <text x="24" y="32" fontSize="14" fill="#3c4043" textAnchor="middle" fontWeight="700" fontFamily="Roboto">18</text>
        </svg>
        <div style={{ fontSize: 14, fontWeight: 600, color: '#3c4043' }}>Google Calendar</div>
        <div style={{ fontSize: 12.5, color: '#5f6368' }}>· יוסי בן-פורת (yuval@ybprojects.com)</div>
        <div style={{ marginRight: 'auto', display: 'flex', gap: 6, alignItems: 'center' }}>
          <button style={{ background: 'transparent', border: '1px solid #dadce0', padding: '4px 8px', borderRadius: 4, fontSize: 11, cursor: 'pointer', color: '#3c4043' }}>היום</button>
          <button style={{ background: 'transparent', border: 'none', padding: 4, cursor: 'pointer' }}><Icon name="chevronR" size={16} color="#5f6368"/></button>
          <button style={{ background: 'transparent', border: 'none', padding: 4, cursor: 'pointer' }}><Icon name="chevron" size={16} color="#5f6368"/></button>
          <div style={{ fontSize: 14, color: '#3c4043', fontWeight: 500, marginRight: 4 }}>13—19 אפר׳ 2026</div>
          <div style={{ fontSize: 10, color: '#5f6368', background: '#e8f0fe', padding: '2px 8px', borderRadius: 10, marginRight: 8 }}>🔄 מסונכרן</div>
        </div>
      </div>

      {/* Legend */}
      <div style={{ padding: '6px 16px', background: '#fafafa', borderBottom: '1px solid #eee', display: 'flex', gap: 14, fontSize: 11, color: '#5f6368' }}>
        <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
          <span style={{ width: 10, height: 10, background: '#d50000', borderRadius: 2 }}/>
          {projectName}
        </span>
        <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
          <span style={{ width: 10, height: 10, background: '#0b8043', borderRadius: 2 }}/>
          פרויקטים אחרים
        </span>
        <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
          <span style={{ width: 10, height: 10, background: '#7986cb', borderRadius: 2 }}/>
          אישי
        </span>
        <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
          <span style={{ width: 10, height: 10, background: '#f6bf26', borderRadius: 2 }}/>
          פגישות
        </span>
      </div>

      {/* Week grid */}
      <div style={{ display: 'grid', gridTemplateColumns: '50px repeat(7, 1fr)', borderBottom: '1px solid #dadce0' }}>
        <div></div>
        {weekDays.map(d => (
          <div key={d.date} style={{ padding: '8px 0', textAlign: 'center', borderLeft: '1px solid #dadce0', background: d.today ? '#e8f0fe' : '#fff' }}>
            <div style={{ fontSize: 10, color: d.today ? '#1967d2' : '#5f6368', textTransform: 'uppercase', fontWeight: 500 }}>{d.label}</div>
            <div style={{ fontSize: 18, color: d.today ? '#1967d2' : '#3c4043', fontWeight: d.today ? 700 : 400, marginTop: 2 }}>
              {d.today ? <span style={{ background: '#1967d2', color: '#fff', width: 28, height: 28, borderRadius: 14, display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>{d.num}</span> : d.num}
            </div>
          </div>
        ))}
      </div>

      {/* Hour grid */}
      <div style={{ display: 'grid', gridTemplateColumns: '50px 1fr', position: 'relative', height: 420, overflow: 'hidden' }}>
        {/* Hour labels */}
        <div>
          {hours.map((h, i) => (
            <div key={h} style={{ height: 42, position: 'relative' }}>
              <div style={{ position: 'absolute', top: -6, right: 6, fontSize: 10, color: '#5f6368' }}>{h}</div>
            </div>
          ))}
        </div>

        {/* Day columns */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', position: 'relative' }}>
          {weekDays.map((d, i) => (
            <div key={d.date} style={{ borderLeft: '1px solid #dadce0', position: 'relative', background: d.today ? '#f8fbff' : '#fff' }}>
              {hours.map((h, j) => (
                <div key={h} style={{ height: 42, borderBottom: '1px solid #f0f0f0' }}/>
              ))}
              {/* Events for this day */}
              {allEvents.filter(e => e.day === d.date).map((e, ei) => {
                const top = timeToOffset(e.time) * 42 / 60;
                const height = e.duration * 42 / 60;
                return (
                  <div
                    key={ei}
                    onClick={() => e.isProject && e.meeting?.reportId && onOpenReport?.(e.meeting.reportId)}
                    style={{
                      position: 'absolute', top, right: 2, left: 2,
                      height: height - 2, background: e.color, color: '#fff',
                      borderRadius: 3, padding: '3px 6px', fontSize: 10.5, lineHeight: 1.3,
                      overflow: 'hidden', cursor: e.isProject ? 'pointer' : 'default',
                      boxShadow: e.isProject ? '0 2px 6px rgba(213,0,0,0.3)' : 'none',
                      border: e.isProject ? '1px solid #b80000' : 'none',
                    }}
                  >
                    <div style={{ fontSize: 9.5, opacity: 0.9 }}>{e.time}</div>
                    <div style={{ fontWeight: 600, whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden' }}>{e.title}</div>
                  </div>
                );
              })}
              {/* "Now" line on today */}
              {d.today && (
                <div style={{ position: 'absolute', top: timeToOffset('10:30') * 42 / 60, right: 0, left: 0, height: 2, background: '#ea4335', zIndex: 5 }}>
                  <div style={{ position: 'absolute', right: -5, top: -4, width: 10, height: 10, background: '#ea4335', borderRadius: 5 }}/>
                </div>
              )}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { ProjectTasksScreen, ProjectMeetingsScreen, AddTaskModal, TaskCard });
})();
