// Live Project Board — ממשק קבלן
// Mobile-first, minimal, practical
(function(){

const { useState, useEffect, useRef } = React;

// ─── helpers ────────────────────────────────────────────────────────────────
const fmtDate = d => {
  if (!d) return '—';
  const [y,m,day] = d.split('-');
  return `${day}/${m}/${y}`;
};

const SEVERITY_LABEL = { critical: 'קריטי', high: 'גבוה', medium: 'בינוני', low: 'נמוך' };
const SEVERITY_COLOR = {
  critical: { bg: '#fee2e2', color: '#dc2626', dot: '#ef4444' },
  high:     { bg: '#ffedd5', color: '#c2410c', dot: '#f97316' },
  medium:   { bg: '#fef3c7', color: '#92400e', dot: '#f59e0b' },
  low:      { bg: '#f0fdf4', color: '#166534', dot: '#22c55e' },
};

// ─── Confirm Modal ───────────────────────────────────────────────────────────
function ConfirmModal({ msg, onConfirm, onCancel }) {
  return (
    <div style={{
      position:'fixed', inset:0, background:'rgba(0,0,0,0.5)',
      display:'flex', alignItems:'flex-end', justifyContent:'center',
      zIndex:9999, padding:'0 0 20px'
    }}>
      <div style={{
        background:'#fff', borderRadius:16, padding:'24px 20px',
        width:'100%', maxWidth:420, margin:'0 16px',
        fontFamily:'Assistant, sans-serif', direction:'rtl',
        boxShadow:'0 -8px 40px rgba(0,0,0,0.15)'
      }}>
        <div style={{ fontSize:15, fontWeight:600, color:'#111827', marginBottom:20, lineHeight:1.5 }}>{msg}</div>
        <div style={{ display:'flex', gap:10 }}>
          <button onClick={onConfirm} style={{
            flex:1, padding:'13px', background:'#1a2c4a', color:'#fff',
            border:'none', borderRadius:10, fontSize:15, fontWeight:700,
            cursor:'pointer', fontFamily:'inherit'
          }}>אישור</button>
          <button onClick={onCancel} style={{
            flex:1, padding:'13px', background:'#f3f4f6', color:'#374151',
            border:'none', borderRadius:10, fontSize:15, fontWeight:600,
            cursor:'pointer', fontFamily:'inherit'
          }}>ביטול</button>
        </div>
      </div>
    </div>
  );
}

// ─── Photo Uploader ──────────────────────────────────────────────────────────
function PhotoInput({ onPhoto }) {
  const refCamera = useRef();
  const refGallery = useRef();
  const handleChange = (e) => {
    const file = e.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = ev => onPhoto(ev.target.result);
    reader.readAsDataURL(file);
  };
  return (
    <div style={{ display:'flex', gap:6 }}>
      <input ref={refCamera} type="file" accept="image/*" capture="environment"
        style={{ display:'none' }} onChange={handleChange}/>
      <input ref={refGallery} type="file" accept="image/*"
        style={{ display:'none' }} onChange={handleChange}/>
      <button onClick={() => refCamera.current.click()} style={{
        display:'flex', alignItems:'center', gap:5,
        padding:'9px 12px', background:'#f0fdf4', color:'#15803d',
        border:'1px solid #bbf7d0', borderRadius:8, fontSize:12,
        fontWeight:600, cursor:'pointer', fontFamily:'inherit'
      }}>📷 צלם</button>
      <button onClick={() => refGallery.current.click()} style={{
        display:'flex', alignItems:'center', gap:5,
        padding:'9px 12px', background:'#eff6ff', color:'#1d4ed8',
        border:'1px solid #bfdbfe', borderRadius:8, fontSize:12,
        fontWeight:600, cursor:'pointer', fontFamily:'inherit'
      }}>🖼️ גלריה</button>
    </div>
  );
}

// ─── Comment Box ─────────────────────────────────────────────────────────────
function CommentBox({ onSave, onCancel }) {
  const [text, setText] = useState('');
  return (
    <div style={{ marginTop:10 }}>
      <textarea value={text} onChange={e => setText(e.target.value)}
        placeholder="כתוב הערה..."
        style={{
          width:'100%', padding:'10px 12px', borderRadius:8,
          border:'1px solid #d1d5db', fontSize:14, fontFamily:'inherit',
          resize:'vertical', minHeight:80, direction:'rtl', boxSizing:'border-box'
        }}/>
      <div style={{ display:'flex', gap:8, marginTop:8 }}>
        <button onClick={() => text.trim() && onSave(text.trim())} style={{
          padding:'8px 16px', background:'#1a2c4a', color:'#fff',
          border:'none', borderRadius:8, fontSize:13, fontWeight:700,
          cursor:'pointer', fontFamily:'inherit'
        }}>שלח</button>
        <button onClick={onCancel} style={{
          padding:'8px 14px', background:'#f3f4f6', color:'#374151',
          border:'none', borderRadius:8, fontSize:13,
          cursor:'pointer', fontFamily:'inherit'
        }}>ביטול</button>
      </div>
    </div>
  );
}

// ─── Date Picker ─────────────────────────────────────────────────────────────
function DatePicker({ value, onSave, onCancel }) {
  const [date, setDate] = useState(value || '');
  return (
    <div style={{ marginTop:10, display:'flex', gap:8, alignItems:'center', flexWrap:'wrap' }}>
      <input type="date" value={date} onChange={e => setDate(e.target.value)}
        style={{
          padding:'9px 12px', borderRadius:8, border:'1px solid #d1d5db',
          fontSize:14, fontFamily:'inherit', direction:'ltr'
        }}/>
      <button onClick={() => date && onSave(date)} style={{
        padding:'9px 16px', background:'#1a2c4a', color:'#fff',
        border:'none', borderRadius:8, fontSize:13, fontWeight:700,
        cursor:'pointer', fontFamily:'inherit'
      }}>עדכן</button>
      <button onClick={onCancel} style={{
        padding:'9px 12px', background:'#f3f4f6', color:'#374151',
        border:'none', borderRadius:8, fontSize:13,
        cursor:'pointer', fontFamily:'inherit'
      }}>ביטול</button>
    </div>
  );
}

// ─── Reject Card ─────────────────────────────────────────────────────────────
function RejectCard({ reject, onMarkDone, onComment, onDateChange, onPhoto }) {
  const [expanded, setExpanded] = useState(false);
  const [showComment, setShowComment] = useState(false);
  const [showDate, setShowDate] = useState(false);
  const [confirm, setConfirm] = useState(null);

  const sev = SEVERITY_COLOR[reject.severity] || SEVERITY_COLOR.medium;
  const isDone = reject.status === 'done';

  const handleMark = () => {
    setConfirm({
      msg: `לסמן את "${reject.title}" כטופל?`,
      action: () => { onMarkDone(reject.id); setConfirm(null); }
    });
  };

  const handleComment = (text) => {
    setConfirm({
      msg: `לשלוח את ההערה: "${text}"?`,
      action: () => { onComment(reject.id, text); setShowComment(false); setConfirm(null); }
    });
  };

  const handleDate = (d) => {
    setConfirm({
      msg: `לעדכן תאריך יעד ל-${fmtDate(d)}?`,
      action: () => { onDateChange(reject.id, d); setShowDate(false); setConfirm(null); }
    });
  };

  const handlePhoto = (dataUrl) => {
    setConfirm({
      msg: 'לשלוח תמונת לאחר תיקון?',
      action: () => { onPhoto(reject.id, dataUrl); setConfirm(null); }
    });
  };

  return (
    <div style={{
      background: isDone ? '#f9fafb' : '#fff',
      border: `1px solid ${isDone ? '#e5e7eb' : '#e5e7eb'}`,
      borderRight: `4px solid ${isDone ? '#10b981' : sev.dot}`,
      borderRadius: 12,
      marginBottom: 10,
      overflow: 'hidden',
      opacity: isDone ? 0.75 : 1,
    }}>
      {/* Main row */}
      <div onClick={() => setExpanded(x => !x)}
        style={{ padding:'14px 16px', cursor:'pointer', display:'flex', gap:12, alignItems:'flex-start' }}>
        <div style={{ flex:1, minWidth:0 }}>
          <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom:4, flexWrap:'wrap' }}>
            {isDone && <span style={{ fontSize:14 }}>✅</span>}
            <span style={{ fontSize:15, fontWeight:700, color: isDone ? '#6b7280' : '#111827' }}>
              {reject.title}
            </span>
          </div>
          <div style={{ display:'flex', gap:6, flexWrap:'wrap', alignItems:'center' }}>
            <span style={{
              fontSize:11, fontWeight:700, padding:'2px 8px', borderRadius:20,
              background: sev.bg, color: sev.color
            }}>{SEVERITY_LABEL[reject.severity] || reject.severity}</span>
            {(reject.trades||[]).map(t => (
              <span key={t} style={{
                fontSize:11, padding:'2px 8px', borderRadius:20,
                background:'#eff6ff', color:'#1d4ed8', fontWeight:600
              }}>{t}</span>
            ))}
            <span style={{ fontSize:11, color:'#9ca3af' }}>יעד: {fmtDate(reject.due)}</span>
          </div>
        </div>
        <span style={{ color:'#9ca3af', fontSize:18, flexShrink:0, marginTop:2 }}>
          {expanded ? '▲' : '▼'}
        </span>
      </div>

      {/* Expanded */}
      {expanded && (
        <div style={{ padding:'0 16px 16px', borderTop:'1px solid #f3f4f6' }}>
          {/* Description */}
          {reject.description && (
            <p style={{ fontSize:13, color:'#4b5563', margin:'12px 0', lineHeight:1.6 }}>
              {reject.description}
            </p>
          )}

          {/* After-fix photos */}
          {reject.afterPhotos && reject.afterPhotos.length > 0 && (
            <div style={{ marginBottom:12 }}>
              <div style={{ fontSize:12, fontWeight:700, color:'#6b7280', marginBottom:6 }}>תמונות לאחר תיקון</div>
              <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
                {reject.afterPhotos.map((p, i) => (
                  <img key={i} src={p} alt="after"
                    style={{ width:72, height:72, objectFit:'cover', borderRadius:8, border:'1px solid #e5e7eb' }}/>
                ))}
              </div>
            </div>
          )}

          {/* Comments */}
          {reject.comments && reject.comments.length > 0 && (
            <div style={{ marginBottom:12 }}>
              {reject.comments.map((c, i) => (
                <div key={i} style={{
                  background:'#f9fafb', borderRadius:8, padding:'8px 12px',
                  fontSize:13, color:'#374151', marginBottom:6,
                  borderRight:'3px solid #b5a882'
                }}>
                  <span style={{ fontWeight:700, color:'#1a2c4a' }}>{c.author}: </span>{c.text}
                  <span style={{ fontSize:11, color:'#9ca3af', marginRight:8 }}>{fmtDate(c.date)}</span>
                </div>
              ))}
            </div>
          )}

          {/* Actions */}
          {!isDone && (
            <div style={{ display:'flex', gap:8, flexWrap:'wrap', marginTop:4 }}>
              <button onClick={handleMark} style={{
                display:'flex', alignItems:'center', gap:6,
                padding:'9px 14px', background:'#f0fdf4', color:'#15803d',
                border:'1px solid #bbf7d0', borderRadius:8, fontSize:13,
                fontWeight:700, cursor:'pointer', fontFamily:'inherit'
              }}>✅ טופל</button>

              <button onClick={() => { setShowComment(x => !x); setShowDate(false); }} style={{
                display:'flex', alignItems:'center', gap:6,
                padding:'9px 14px', background:'#eff6ff', color:'#1d4ed8',
                border:'1px solid #bfdbfe', borderRadius:8, fontSize:13,
                fontWeight:600, cursor:'pointer', fontFamily:'inherit'
              }}>💬 הערה</button>

              <button onClick={() => { setShowDate(x => !x); setShowComment(false); }} style={{
                display:'flex', alignItems:'center', gap:6,
                padding:'9px 14px', background:'#fef3c7', color:'#92400e',
                border:'1px solid #fde68a', borderRadius:8, fontSize:13,
                fontWeight:600, cursor:'pointer', fontFamily:'inherit'
              }}>📅 תאריך</button>

              <PhotoInput onPhoto={handlePhoto}/>
            </div>
          )}

          {showComment && !isDone && (
            <CommentBox onSave={handleComment} onCancel={() => setShowComment(false)}/>
          )}
          {showDate && !isDone && (
            <DatePicker value={reject.due} onSave={handleDate} onCancel={() => setShowDate(false)}/>
          )}
        </div>
      )}

      {confirm && (
        <ConfirmModal msg={confirm.msg} onConfirm={confirm.action} onCancel={() => setConfirm(null)}/>
      )}
    </div>
  );
}

// ─── Report Source Badge ─────────────────────────────────────────────────────
function ReportSourceBadge({ task, reports, onViewReport }) {
  const [showSheet, setShowSheet] = useState(false);

  // מצא את הדוח המקושר
  const sourceReport = React.useMemo(() => {
    if (!task.sourceReportId) return null;
    return (reports || []).find(r => r.id === task.sourceReportId) || null;
  }, [task.sourceReportId, reports]);

  const sourceLabel = React.useMemo(() => {
    if (sourceReport) {
      const kindMap = { daily: 'דוח יומי', weekly: 'דוח שבועי', rejects: "דו\"ח ריג'קטים", infra: 'תיעוד תשתיות' };
      const d = sourceReport.date ? (() => {
        const [y,m,day] = sourceReport.date.split('-');
        return `${day}/${m}/${y}`;
      })() : '';
      return `${kindMap[sourceReport.kind] || 'דוח'} · ${d}`;
    }
    if (task.source === 'pm') return 'משימת מנהל';
    if (task.source === 'reject') return "ריג'קט";
    if (task.sourceReportId) return task.sourceReportId;
    return null;
  }, [sourceReport, task]);

  if (!sourceLabel) return null;

  return (
    <>
      <button
        onClick={e => { e.stopPropagation(); if (sourceReport && onViewReport) setShowSheet(true); }}
        style={{
          display: 'inline-flex', alignItems: 'center', gap: 4,
          fontSize: 11, padding: '2px 8px', borderRadius: 20,
          background: sourceReport && onViewReport ? '#f0f4ff' : '#f3f4f6',
          color: sourceReport && onViewReport ? '#3b5bdb' : '#6b7280',
          border: sourceReport && onViewReport ? '1px solid #c5d0fc' : '1px solid #e5e7eb',
          fontWeight: 600, cursor: sourceReport && onViewReport ? 'pointer' : 'default',
          fontFamily: 'inherit',
        }}
      >
        📋 {sourceLabel}
        {sourceReport && onViewReport && <span style={{ fontSize: 10 }}>›</span>}
      </button>

      {/* Bottom sheet — פרטי הדוח */}
      {showSheet && sourceReport && (
        <div
          style={{
            position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)',
            zIndex: 9999, display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
          }}
          onClick={() => setShowSheet(false)}
        >
          <div
            style={{
              background: '#fff', borderRadius: '16px 16px 0 0',
              width: '100%', maxWidth: 480, padding: '20px 20px 36px',
              fontFamily: 'Assistant, sans-serif', direction: 'rtl',
              boxShadow: '0 -8px 40px rgba(0,0,0,0.18)',
            }}
            onClick={e => e.stopPropagation()}
          >
            {/* Handle */}
            <div style={{ width: 36, height: 4, background: '#e5e7eb', borderRadius: 2, margin: '0 auto 16px' }}></div>
            
            <div style={{ fontSize: 13, color: '#9ca3af', marginBottom: 4 }}>מקור המשימה</div>
            <div style={{ fontSize: 18, fontWeight: 800, color: '#111827', marginBottom: 6 }}>
              {sourceReport.title || sourceReport.id}
            </div>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 16 }}>
              {(() => {
                const kindMap = { daily: 'דוח יומי', weekly: 'דוח שבועי', rejects: "ריג'קטים", infra: 'תשתיות' };
                return (
                  <span style={{ fontSize: 12, padding: '3px 10px', borderRadius: 20, background: '#eff6ff', color: '#1d4ed8', fontWeight: 700 }}>
                    {kindMap[sourceReport.kind] || 'דוח'}
                  </span>
                );
              })()}
              <span style={{ fontSize: 12, color: '#6b7280' }}>
                📅 {sourceReport.date ? (() => { const [y,m,d] = sourceReport.date.split('-'); return `${d}/${m}/${y}`; })() : ''}
              </span>
              <span style={{ fontSize: 12, color: '#6b7280' }}>👤 {sourceReport.author}</span>
            </div>

            {/* Task title */}
            <div style={{ background: '#f8fafc', borderRadius: 10, padding: '12px 14px', marginBottom: 20, borderRight: '4px solid #f59e0b' }}>
              <div style={{ fontSize: 11, color: '#9ca3af', marginBottom: 4 }}>המשימה</div>
              <div style={{ fontSize: 14, fontWeight: 700, color: '#111827' }}>{task.title}</div>
            </div>

            <div style={{ display: 'flex', gap: 10 }}>
              <button
                onClick={() => { setShowSheet(false); onViewReport(sourceReport.id); }}
                style={{
                  flex: 1, padding: '13px', background: '#1a2c4a', color: '#fff',
                  border: 'none', borderRadius: 10, fontSize: 15, fontWeight: 700,
                  cursor: 'pointer', fontFamily: 'inherit',
                }}
              >פתח דוח מלא</button>
              <button
                onClick={() => setShowSheet(false)}
                style={{
                  padding: '13px 18px', background: '#f3f4f6', color: '#374151',
                  border: 'none', borderRadius: 10, fontSize: 14, fontWeight: 600,
                  cursor: 'pointer', fontFamily: 'inherit',
                }}
              >סגור</button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}


function ContractorBoard({ contractorName, projectId: initialProjectId, onBack, onViewReport }) {
  const [rejects, setRejects] = useState([]);
  const [tasks, setTasks] = useState([]);
  const [reports, setReports] = useState([]);
  const [filterTrade, setFilterTrade] = useState('');
  const [filterText, setFilterText] = useState('');
  const [tab, setTab] = useState('rejects'); // rejects | reports
  const [lastRefresh, setLastRefresh] = useState(null);

  // ── Multi-project support ────────────────────────────────────────────────
  const [myProjects, setMyProjects] = useState([]);
  const [projectId, setProjectId] = useState(initialProjectId);

  // Find all projects where this contractor has rejects or tasks
  useEffect(() => {
    const store = SyncStore.get();
    if (!store) return;
    const allProjects = window.YBP_DATA?.projects || [];
    const found = [];
    allProjects.forEach(proj => {
      const projReports = (store.reports || []).filter(r => r.projectId === proj.id);
      let hasWork = false;
      projReports.forEach(rep => {
        if (rep.rejects?.some(rj =>
          !contractorName ||
          (rj.assignee||'').includes(contractorName) ||
          (rj.trades||[]).some(t => contractorName.includes(t))
        )) hasWork = true;
      });
      const tasks = (store.tasks || []).filter(t =>
        t.projectId === proj.id &&
        t.status !== 'archived' &&
        (!contractorName || (t.assignee||'').includes(contractorName))
      );
      if (hasWork || tasks.length > 0) found.push(proj);
    });
    // Always include the initial project
    if (!found.find(p => p.id === initialProjectId)) {
      const initProj = allProjects.find(p => p.id === initialProjectId);
      if (initProj) found.unshift(initProj);
    }
    setMyProjects(found);
  }, [contractorName, initialProjectId]);

  // All trades from rejects
  const allTrades = [...new Set(rejects.flatMap(r => r.trades || []))].sort();

  // Load on mount + when projectId changes
  useEffect(() => {
    loadData();
    const unsub = SyncStore.subscribe(() => loadData());
    // Save on page hide / close
    const handleHide = () => saveSession();
    window.addEventListener('pagehide', handleHide);
    window.addEventListener('beforeunload', handleHide);
    return () => {
      unsub && unsub();
      window.removeEventListener('pagehide', handleHide);
      window.removeEventListener('beforeunload', handleHide);
    };
  }, [projectId]);

  const loadData = () => {
    const store = SyncStore.get();
    if (!store) return;

    // משימות לפרויקט — מסונן לפי קבלן
    const projTasks = (store.tasks || []).filter(t => t.projectId === projectId && t.status !== 'archived');
    const contrTasks = contractorName
      ? projTasks.filter(t => (t.assignee || '').includes(contractorName))
      : projTasks;

    // ממיר tasks לפורמט RejectCard
    const tasksAsRejects = contrTasks.map(t => ({
      id: t.id,
      title: t.title,
      description: t.description || '',
      trades: t.trades || [],
      assignee: t.assignee || '',
      severity: t.severity || 'medium',
      due: t.due || '',
      status: t.status || 'open',
      comments: t.comments || [],
      afterPhotos: t.afterPhotos || [],
      photos: t.photos || [],
      fromReport: t.sourceReportId || (t.source === 'pm' ? 'משימת מנהל' : 'ריג׳קט'),
      source: t.source,
      _taskId: t.id,
    }));

    setRejects(tasksAsRejects);
    setReports((store.reports || []).filter(r => r.projectId === projectId));
    setTasks(contrTasks);
    setLastRefresh(new Date());
  };

  const saveSession = () => {};

  // Mutations — עכשיו דרך SyncStore
  const markDone = (taskId) => {
    SyncStore.updateTask(taskId, { status: 'done', completedAt: new Date().toISOString() });
  };

  const addComment = (taskId, text) => {
    const comment = { text, author: contractorName || 'קבלן', date: new Date().toISOString().slice(0,10) };
    SyncStore.addComment(taskId, comment);
  };

  const changeDate = (taskId, date) => {
    SyncStore.updateTask(taskId, { due: date });
  };

  const addPhoto = (taskId, dataUrl) => {
    const store = SyncStore.get();
    const task = (store.tasks || []).find(t => t.id === taskId);
    const afterPhotos = [...(task?.afterPhotos || []), dataUrl];
    SyncStore.updateTask(taskId, { afterPhotos });
  };

  // Filtered rejects
  const visibleRejects = rejects.filter(rj => {
    const matchTrade = !filterTrade || (rj.trades||[]).includes(filterTrade);
    const matchText = !filterText ||
      rj.title.includes(filterText) ||
      (rj.assignee||'').includes(filterText) ||
      (rj.description||'').includes(filterText);
    return matchTrade && matchText;
  });

  const openCount = visibleRejects.filter(r => r.status !== 'done').length;
  const doneCount = visibleRejects.filter(r => r.status === 'done').length;

  // Project info
  const proj = (window.YBP_DATA?.projects || []).find(p => p.id === projectId) || {};

  return (
    <div style={{
      minHeight:'100vh', background:'#f6f7f9',
      fontFamily:'Assistant, sans-serif', direction:'rtl',
      maxWidth:480, margin:'0 auto',
    }}>

      {/* ── Header ── */}
      <div style={{
        background:'#1a2c4a', color:'#fff',
        padding:'0',
        position:'sticky', top:0, zIndex:100,
        boxShadow:'0 2px 12px rgba(0,0,0,0.15)'
      }}>
        {/* Top bar */}
        <div style={{
          display:'flex', alignItems:'center', gap:12,
          padding:'14px 16px 10px',
        }}>
          <button onClick={onBack} style={{
            background:'rgba(255,255,255,0.12)', border:'none', borderRadius:8,
            width:36, height:36, display:'flex', alignItems:'center', justifyContent:'center',
            cursor:'pointer', color:'#fff', flexShrink:0
          }}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <polyline points="15 18 9 12 15 6"/>
            </svg>
          </button>
          <div style={{ flex:1, minWidth:0 }}>
            <div style={{ fontSize:11, opacity:0.65, marginBottom:1 }}>YBPROJECTS · לוח קבלן</div>
            <div style={{ fontSize:16, fontWeight:800, letterSpacing:-0.3, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>
              {contractorName || 'כל הקבלנים'}
            </div>
          </div>
          <img src="assets/ybp-logo.png" alt="YBP"
            style={{ height:34, objectFit:'contain', opacity:0.9, flexShrink:0 }}
            onError={e => { e.target.style.display='none'; }}/>
        </div>

        {/* Project selector */}
        <div style={{ padding:'0 16px 10px' }}>
          {myProjects.length > 1 ? (
            <div>
              <div style={{ fontSize:10, color:'rgba(255,255,255,0.5)', marginBottom:5, letterSpacing:0.5 }}>בחר פרויקט</div>
              <div style={{ display:'flex', gap:6, overflowX:'auto', paddingBottom:2 }}>
                {myProjects.map(p => (
                  <button key={p.id} onClick={() => { setProjectId(p.id); setFilterTrade(''); setFilterText(''); }}
                    style={{
                      flexShrink:0, padding:'5px 12px', borderRadius:20,
                      border: p.id === projectId ? '1.5px solid #b5a882' : '1.5px solid rgba(255,255,255,0.2)',
                      background: p.id === projectId ? 'rgba(181,168,130,0.25)' : 'rgba(255,255,255,0.07)',
                      color: p.id === projectId ? '#d4c9aa' : 'rgba(255,255,255,0.65)',
                      fontSize:12, fontWeight: p.id === projectId ? 700 : 500,
                      cursor:'pointer', fontFamily:'inherit', whiteSpace:'nowrap',
                    }}>
                    {p.id === projectId ? '📍 ' : ''}{p.name}
                  </button>
                ))}
              </div>
            </div>
          ) : (
            <div style={{ fontSize:13, opacity:0.8 }}>📍 {proj.name || 'פרויקט'}</div>
          )}
        </div>

        {/* Refresh button */}
        <div style={{ display:'flex', justifyContent:'flex-end', padding:'0 16px 8px', marginTop: myProjects.length > 1 ? 0 : -8 }}>
          <button onClick={loadData} style={{
            background:'rgba(255,255,255,0.1)', border:'none', borderRadius:6,
            padding:'4px 10px', color:'rgba(255,255,255,0.8)', fontSize:11,
            cursor:'pointer', fontFamily:'inherit'
          }}>
            🔄 {lastRefresh ? lastRefresh.toLocaleTimeString('he-IL', {hour:'2-digit',minute:'2-digit'}) : 'רענן'}
          </button>
        </div>

        {/* Gold line */}
        <div style={{ height:3, background:'linear-gradient(90deg,#b5a882,#d4c9aa,#b5a882)' }}/>
      </div>

      {/* ── Stats ── */}
      <div style={{
        display:'grid', gridTemplateColumns:'1fr 1fr 1fr',
        gap:1, background:'#e5e7eb', margin:'0 0 0'
      }}>
        {[
          { val: openCount, label: 'פתוחים', color: '#dc2626', bg:'#fff' },
          { val: doneCount, label: 'טופלו', color: '#16a34a', bg:'#fff' },
          { val: rejects.length, label: 'סה״כ', color: '#374151', bg:'#fff' },
        ].map(s => (
          <div key={s.label} style={{
            background:s.bg, padding:'14px 0', textAlign:'center'
          }}>
            <div style={{ fontSize:22, fontWeight:800, color:s.color }}>{s.val}</div>
            <div style={{ fontSize:11, color:'#6b7280', fontWeight:600 }}>{s.label}</div>
          </div>
        ))}
      </div>

      {/* ── Tabs ── */}
      <div style={{
        display:'flex', background:'#fff',
        borderBottom:'1px solid #e5e7eb',
      }}>
        {[
          { k:'rejects', label:`ריג'קטים (${openCount})` },
          { k:'tasks', label:`משימות (${tasks.filter(t=>t.status!=='done').length})` },
          { k:'reports', label:`דוחות (${reports.length})` },
        ].map(t => (
          <button key={t.k} onClick={() => setTab(t.k)} style={{
            flex:1, padding:'13px 8px',
            background:'transparent', border:'none',
            borderBottom: tab===t.k ? '3px solid #1a2c4a' : '3px solid transparent',
            fontSize:14, fontWeight: tab===t.k ? 700 : 500,
            color: tab===t.k ? '#1a2c4a' : '#6b7280',
            cursor:'pointer', fontFamily:'inherit', transition:'all 0.15s'
          }}>{t.label}</button>
        ))}
      </div>

      {/* ── Content ── */}
      <div style={{ padding:'12px 14px 80px' }}>

        {tab === 'rejects' && <>
          {/* Filters */}
          <div style={{ marginBottom:12 }}>
            <input value={filterText} onChange={e => setFilterText(e.target.value)}
              placeholder="חיפוש לפי שם..."
              style={{
                width:'100%', padding:'10px 14px', borderRadius:8,
                border:'1px solid #e5e7eb', fontSize:14, fontFamily:'inherit',
                background:'#fff', boxSizing:'border-box', marginBottom:8,
                direction:'rtl'
              }}/>
            {allTrades.length > 0 && (
              <div style={{ display:'flex', gap:6, flexWrap:'wrap' }}>
                <button onClick={() => setFilterTrade('')} style={{
                  padding:'6px 12px', borderRadius:20, fontSize:12, fontWeight:600,
                  border:'none', cursor:'pointer', fontFamily:'inherit',
                  background: !filterTrade ? '#1a2c4a' : '#f3f4f6',
                  color: !filterTrade ? '#fff' : '#374151',
                }}>הכל</button>
                {allTrades.map(t => (
                  <button key={t} onClick={() => setFilterTrade(t === filterTrade ? '' : t)} style={{
                    padding:'6px 12px', borderRadius:20, fontSize:12, fontWeight:600,
                    border:'none', cursor:'pointer', fontFamily:'inherit',
                    background: filterTrade === t ? '#1d4ed8' : '#eff6ff',
                    color: filterTrade === t ? '#fff' : '#1d4ed8',
                  }}>{t}</button>
                ))}
              </div>
            )}
          </div>

          {/* Open rejects first */}
          {visibleRejects.filter(r => r.status !== 'done').length > 0 && (
            <div style={{ marginBottom:4 }}>
              <div style={{ fontSize:11, fontWeight:800, color:'#6b7280', letterSpacing:0.5, textTransform:'uppercase', marginBottom:8 }}>
                פתוחים לטיפול — {visibleRejects.filter(r => r.status !== 'done').length}
              </div>
              {visibleRejects.filter(r => r.status !== 'done').map(rj => (
                <RejectCard key={rj.id} reject={rj}
                  onMarkDone={markDone} onComment={addComment}
                  onDateChange={changeDate} onPhoto={addPhoto}/>
              ))}
            </div>
          )}

          {/* Done rejects */}
          {visibleRejects.filter(r => r.status === 'done').length > 0 && (
            <div style={{ marginTop:16 }}>
              <div style={{ fontSize:11, fontWeight:800, color:'#6b7280', letterSpacing:0.5, textTransform:'uppercase', marginBottom:8 }}>
                טופלו ✅ — {visibleRejects.filter(r => r.status === 'done').length}
              </div>
              {visibleRejects.filter(r => r.status === 'done').map(rj => (
                <RejectCard key={rj.id} reject={rj}
                  onMarkDone={markDone} onComment={addComment}
                  onDateChange={changeDate} onPhoto={addPhoto}/>
              ))}
            </div>
          )}

          {visibleRejects.length === 0 && (
            <div style={{
              textAlign:'center', padding:'60px 20px',
              color:'#9ca3af', fontSize:14
            }}>
              <div style={{ fontSize:40, marginBottom:12 }}>✅</div>
              <div style={{ fontWeight:700, color:'#374151', marginBottom:4 }}>אין ריג'קטים פתוחים!</div>
              <div>כל המשימות טופלו</div>
            </div>
          )}
        </>}

        {tab === 'tasks' && <>
          {tasks.length === 0 && (
            <div style={{ textAlign:'center', padding:'60px 20px', color:'#9ca3af', fontSize:14 }}>
              <div style={{ fontSize:40, marginBottom:12 }}>✅</div>
              <div style={{ fontWeight:700, color:'#374151', marginBottom:4 }}>אין משימות פתוחות!</div>
            </div>
          )}
          {tasks.filter(t => t.status !== 'done').length > 0 && (
            <div style={{ marginBottom:16 }}>
              <div style={{ fontSize:11, fontWeight:800, color:'#6b7280', letterSpacing:0.5, textTransform:'uppercase', marginBottom:8 }}>פתוחות — {tasks.filter(t=>t.status!=='done').length}</div>
              {tasks.filter(t => t.status !== 'done').map(task => {
            const srcPhotos = task.photos || (task.photo ? [task.photo] : []);
            return (
              <div key={task.id} style={{
                background:'#fff', border:'1px solid #e5e7eb',
                borderRight:'4px solid #f59e0b',
                borderRadius:12, marginBottom:8,
                overflow:'hidden',
              }}>
                {/* תמונות מקור — אם קיימות */}
                {srcPhotos.length > 0 && (
                  <div style={{ display:'flex', gap:2, padding:'8px 8px 0' }}>
                    {srcPhotos.slice(0,4).map((p,i) => (
                      <img key={i} src={p} alt="תמונת בעיה"
                        style={{ width:64, height:52, objectFit:'cover', borderRadius:6, border:'1px solid #e5e7eb', flexShrink:0 }}/>
                    ))}
                    {srcPhotos.length > 4 && (
                      <div style={{
                        width:64, height:52, borderRadius:6, background:'#f3f4f6',
                        display:'flex', alignItems:'center', justifyContent:'center',
                        fontSize:12, fontWeight:700, color:'#6b7280', flexShrink:0
                      }}>+{srcPhotos.length - 4}</div>
                    )}
                  </div>
                )}
                <div style={{ padding:'12px 16px', display:'flex', gap:12, alignItems:'flex-start' }}>
                  <div style={{ flex:1 }}>
                    <div style={{ fontSize:14, fontWeight:700, color:'#111827', marginBottom:6 }}>{task.title}</div>
                    <div style={{ display:'flex', gap:6, flexWrap:'wrap', alignItems:'center' }}>
                      {task.due && <span style={{ fontSize:11, color:'#6b7280' }}>📅 {fmtDate(task.due)}</span>}
                      {task.location && <span style={{ fontSize:11, color:'#6b7280' }}>📍 {task.location}</span>}
                      {task.priority && <span style={{ fontSize:11, background:'#fef3c7', color:'#92400e', padding:'1px 7px', borderRadius:10, fontWeight:600 }}>{task.priority}</span>}
                      <ReportSourceBadge task={task} reports={reports} onViewReport={onViewReport}/>
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
            </div>
          )}
          {tasks.filter(t => t.status === 'done').length > 0 && (
            <div>
              <div style={{ fontSize:11, fontWeight:800, color:'#6b7280', letterSpacing:0.5, textTransform:'uppercase', marginBottom:8 }}>הושלמו ✅ — {tasks.filter(t=>t.status==='done').length}</div>
              {tasks.filter(t => t.status === 'done').map(task => (
                <div key={task.id} style={{
                  background:'#f9fafb', border:'1px solid #e5e7eb',
                  borderRight:'4px solid #10b981',
                  borderRadius:12, padding:'14px 16px', marginBottom:8,
                  opacity:0.7
                }}>
                  <div style={{ fontSize:14, fontWeight:600, color:'#6b7280' }}>✅ {task.title}</div>
                </div>
              ))}
            </div>
          )}
        </>}

        {tab === 'reports' && <>
          {reports.length === 0 && (
            <div style={{
              textAlign:'center', padding:'60px 20px',
              color:'#9ca3af', fontSize:14
            }}>
              <div style={{ fontSize:40, marginBottom:12 }}>📋</div>
              <div>אין דוחות עדיין</div>
            </div>
          )}
          {reports.slice().sort((a,b) => (b.date||'').localeCompare(a.date||'')).map(rep => {
            const kindMap = { daily:'דוח יומי', weekly:'דוח שבועי', rejects:"ריג'קטים", infra:'תשתיות' };
            const kindIcon = { daily:'📝', weekly:'📊', rejects:'🔴', infra:'🏗️' };
            const kindColor = { daily:'#eff6ff', weekly:'#f3e8ff', rejects:'#fee2e2', infra:'#f0fdf4' };
            const kindTextColor = { daily:'#1d4ed8', weekly:'#7c3aed', rejects:'#dc2626', infra:'#15803d' };
            const isClickable = !!onViewReport;
            return (
              <div key={rep.id}
                onClick={() => isClickable && onViewReport(rep.id)}
                style={{
                  background:'#fff', border:'1px solid #e5e7eb',
                  borderRadius:12, padding:'14px 16px', marginBottom:10,
                  display:'flex', alignItems:'center', gap:12,
                  cursor: isClickable ? 'pointer' : 'default',
                  transition:'background 0.12s',
                }}
                onMouseEnter={e => { if(isClickable) e.currentTarget.style.background='#f8fafc'; }}
                onMouseLeave={e => { if(isClickable) e.currentTarget.style.background='#fff'; }}
              >
                <div style={{
                  width:42, height:42, borderRadius:10,
                  background: kindColor[rep.kind] || '#eff6ff',
                  display:'flex', alignItems:'center', justifyContent:'center',
                  fontSize:20, flexShrink:0
                }}>
                  {kindIcon[rep.kind] || '📋'}
                </div>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontSize:14, fontWeight:700, color:'#111827', marginBottom:3, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>
                    {rep.title || rep.id}
                  </div>
                  <div style={{ display:'flex', gap:8, alignItems:'center', flexWrap:'wrap' }}>
                    <span style={{ fontSize:11, padding:'1px 7px', borderRadius:10, background: kindColor[rep.kind]||'#eff6ff', color: kindTextColor[rep.kind]||'#1d4ed8', fontWeight:700 }}>
                      {kindMap[rep.kind] || 'דוח'}
                    </span>
                    <span style={{ fontSize:11, color:'#6b7280' }}>
                      {rep.date ? (() => { const [y,m,d] = rep.date.split('-'); return `${d}/${m}/${y}`; })() : ''}
                    </span>
                    <span style={{ fontSize:11, color:'#9ca3af' }}>👤 {rep.author}</span>
                  </div>
                </div>
                {isClickable && (
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#9ca3af" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                    <polyline points="15 18 9 12 15 6"/>
                  </svg>
                )}
              </div>
            );
          })}
        </>}
      </div>

      {/* ── Bottom CTA ── */}
      {tab === 'rejects' && openCount > 0 && (
        <div style={{
          position:'fixed', bottom:0, right:0, left:0,
          background:'#fff', borderTop:'1px solid #e5e7eb',
          padding:'12px 16px', maxWidth:480, margin:'0 auto',
          boxShadow:'0 -4px 20px rgba(0,0,0,0.08)'
        }}>
          <div style={{ fontSize:12, color:'#6b7280', textAlign:'center' }}>
            {openCount} ריג'קטים מחכים לטיפול שלך
          </div>
        </div>
      )}
    </div>
  );
}

window.ContractorBoard = ContractorBoard;
})();
