// Variation 1: Project Detail — sidebar-driven navigation (no internal tabs)
(function(){
const { useState, useEffect } = React;

const PM_LIST = [
  { key: 'nathan', name: 'נתן'  },
  { key: 'yaniv',  name: 'יניב' },
  { key: 'matan',  name: 'מתן'  },
  { key: 'barak',  name: 'ברק'  },
  { key: 'tal',    name: 'טל'   },
];

function PmEditorModal({ project, onSave, onClose }) {
  const initialPms = Array.isArray(project.pms) && project.pms.length
    ? project.pms
    : (project.pmKey ? [{ key: project.pmKey, name: project.pm || project.pmKey }] : []);
  const [pms, setPms] = useState(initialPms);
  const [adding, setAdding] = useState('');

  const remove = key => setPms(pms.filter(p => p.key !== key));
  const add = () => {
    const pm = PM_LIST.find(p => p.key === adding);
    if (!pm || pms.some(p => p.key === pm.key)) return;
    setPms([...pms, pm]);
    setAdding('');
  };
  const available = PM_LIST.filter(p => !pms.some(existing => existing.key === p.key));

  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)', zIndex: 9000,
      display: 'flex', alignItems: 'center', justifyContent: 'center',
    }} onClick={onClose}>
      <div style={{
        background: '#fff', borderRadius: 12, padding: 24, width: 320, maxWidth: '90vw',
        boxShadow: '0 20px 60px rgba(0,0,0,0.25)', direction: 'rtl',
      }} onClick={e => e.stopPropagation()}>
        <div style={{ fontSize: 16, fontWeight: 700, color: '#111827', marginBottom: 16 }}>
          עריכת מנהל פרויקט
        </div>
        <div style={{ fontSize: 12, color: '#6b7280', marginBottom: 8 }}>מנהלים נוכחיים:</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 14, minHeight: 32 }}>
          {pms.length === 0 && <span style={{ fontSize: 12, color: '#9ca3af' }}>אין מנהל מוגדר</span>}
          {pms.map(pm => (
            <span key={pm.key} style={{
              display: 'inline-flex', alignItems: 'center', gap: 4,
              background: '#eff6ff', color: '#1d4ed8', borderRadius: 99,
              padding: '3px 10px', fontSize: 13, fontWeight: 600,
            }}>
              {pm.name}
              <button onClick={() => remove(pm.key)} style={{
                background: 'none', border: 'none', cursor: 'pointer',
                color: '#6b7280', padding: 0, fontSize: 14, lineHeight: 1,
              }}>×</button>
            </span>
          ))}
        </div>
        {available.length > 0 && (
          <div style={{ display: 'flex', gap: 6, marginBottom: 16 }}>
            <select value={adding} onChange={e => setAdding(e.target.value)} style={{
              flex: 1, padding: '7px 10px', borderRadius: 6, border: '1px solid #e5e7eb',
              fontSize: 13, fontFamily: 'inherit', direction: 'rtl',
            }}>
              <option value="">+ הוסף מנהל</option>
              {available.map(pm => <option key={pm.key} value={pm.key}>{pm.name}</option>)}
            </select>
            <button onClick={add} disabled={!adding} style={{
              padding: '7px 14px', borderRadius: 6, border: 'none',
              background: adding ? '#2563eb' : '#e5e7eb', color: adding ? '#fff' : '#9ca3af',
              fontWeight: 700, cursor: adding ? 'pointer' : 'default', fontSize: 13, fontFamily: 'inherit',
            }}>הוסף</button>
          </div>
        )}
        <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
          <button onClick={onClose} style={{
            padding: '8px 18px', borderRadius: 6, border: '1px solid #e5e7eb',
            background: '#fff', color: '#6b7280', fontSize: 13, fontWeight: 600,
            cursor: 'pointer', fontFamily: 'inherit',
          }}>ביטול</button>
          <button onClick={() => onSave(pms)} style={{
            padding: '8px 18px', borderRadius: 6, border: 'none',
            background: '#059669', color: '#fff', fontSize: 13, fontWeight: 700,
            cursor: 'pointer', fontFamily: 'inherit',
          }}>שמור</button>
        </div>
      </div>
    </div>
  );
}

function savePmToProject(projectId, newPms) {
  const primary = newPms[0] || null;
  const updateProj = p => ({ ...p, pm: primary ? primary.name : '', pmKey: primary ? primary.key : '', pms: newPms });
  // Update YBP_DATA in-memory
  if (window.YBP_DATA) {
    const idx = (window.YBP_DATA.projects || []).findIndex(p => p.id === projectId);
    if (idx !== -1) window.YBP_DATA.projects[idx] = updateProj(window.YBP_DATA.projects[idx]);
    if (window.YBP_DATA._allProjects) {
      const ai = window.YBP_DATA._allProjects.findIndex(p => p.id === projectId);
      if (ai !== -1) window.YBP_DATA._allProjects[ai] = updateProj(window.YBP_DATA._allProjects[ai]);
    }
  }
  // Update ybp_user_projects in localStorage
  try {
    const userProjs = JSON.parse(localStorage.getItem('ybp_user_projects') || '[]');
    const idx = userProjs.findIndex(p => p.id === projectId);
    const src = (window.YBP_DATA && window.YBP_DATA.projects.find(p => p.id === projectId)) || {};
    if (idx !== -1) { userProjs[idx] = updateProj(userProjs[idx]); }
    else { userProjs.unshift(updateProj(src)); }
    localStorage.setItem('ybp_user_projects', JSON.stringify(userProjs));
  } catch (_) {}
  // Shadow-write to Supabase via cloudSave
  try {
    const syncStore = JSON.parse(localStorage.getItem('ybp_sync_store') || '{}');
    if (typeof window.cloudSave === 'function') window.cloudSave('sync_store', syncStore);
  } catch (_) {}
  // Audit
  if (window.YBP_AUTH && window.YBP_AUTH.appendAuditEvent) {
    window.YBP_AUTH.appendAuditEvent({ action: 'pm_changed', projectId, to: newPms, ts: Date.now() });
  }
}

const V1ProjectDetail = ({ projectId, onBack, onOpenClient, onOpenTasks, onOpenReports, onOpenBudget, onOpenGantt, onNewDaily, onOpenQuotes, onOpenPayments, onOpenTenders, onOpenProtocols, onOpenMeetings, onOpenBooklet, onOpenSiteDoc, onOpenProjContacts, onNav }) => {
  const [, forceUpdate] = useState(0);
  const project = YBP_DATA.projects.find(p => p.id === projectId) || YBP_DATA.projects[0];
  const detail = YBP_DATA.projectDetail;
  const [subView, setSubView] = useState('overview');
  const [showPmEditor, setShowPmEditor] = useState(false);
  const { isMobile, isLandscape } = useViewport();

  const handlePmSave = pms => {
    savePmToProject(project.id, pms);
    setShowPmEditor(false);
    forceUpdate(n => n + 1);
  };

  const pmLabel = (() => {
    if (Array.isArray(project.pms) && project.pms.length) return project.pms.map(p => p.name).join(', ');
    return project.pm || '';
  })();

  // projectNav — כל הפריטים לסיידבר
  const projectNavData = {
    projectName: project.name,
    overview: [
      { icon: '🏠', label: 'סקירה',           subView: 'overview',     onClick: () => setSubView('overview') },
      { icon: '📡', label: 'עדכונים',          subView: 'updates',      onClick: () => setSubView('updates') },
      { icon: '✅', label: 'משימות',           subView: 'tasks',        onClick: () => setSubView('tasks') },
      { icon: '📁', label: 'מסמכים',           subView: 'docs',         onClick: () => setSubView('docs') },
      { icon: '👷', label: 'צוות וקבלנים',     subView: 'team',         onClick: () => setSubView('team') },
    ],
    finance: [
      { icon: '📑', label: 'הצעות מחיר',  subView: 'quotes',    onClick: onOpenQuotes },
      { icon: '💸', label: 'תשלומים',      subView: 'payments',  onClick: onOpenPayments },
      { icon: '📊', label: 'תקציב',        subView: 'budget',    onClick: onOpenBudget },
    ],
    reports: [
      { icon: '📝', label: 'דוח יומי חדש', subView: 'newDaily',  onClick: onNewDaily },
      { icon: '📈', label: 'כל הדוחות',    subView: 'reports',   onClick: onOpenReports },
      { icon: '📸', label: 'תיעוד אתר',    subView: 'siteDoc',   onClick: onOpenSiteDoc },
    ],
    manage: [
      { icon: '📅', label: 'גאנט',           subView: 'gantt',      onClick: onOpenGantt },
      { icon: '🤝', label: 'פגישות',          subView: 'meetings',   onClick: onOpenMeetings },
      { icon: '📬', label: 'מכרזים',          subView: 'tenders',    onClick: onOpenTenders },
      { icon: '📝', label: 'פרוטוקולים',      subView: 'protocols',  onClick: onOpenProtocols },
      { icon: '📋', label: 'חוברת פרויקט',   subView: 'booklet',    onClick: onOpenBooklet },
      { icon: '👥', label: 'אנשי קשר',        subView: 'contacts',   onClick: onOpenProjContacts },
    ],
    onOpenDrive: typeof DriveButton !== 'undefined' ? () => {
      const driveBtn = document.querySelector('[data-drive-trigger]');
      if (driveBtn) driveBtn.click();
    } : null,
  };

  return (
    <>
    {showPmEditor && <PmEditorModal project={project} onSave={handlePmSave} onClose={() => setShowPmEditor(false)} />}
    <V1Shell
      active="list"
      onNav={onNav}
      onBack={onBack}
      title={project.name}
      subtitle={`${project.client} • ${project.address}`}
      projectNav={projectNavData}
      activeSubView={subView}
      actions={
        <>
          <button onClick={() => setShowPmEditor(true)} title="ערוך מנהל פרויקט" style={{
            display: 'flex', alignItems: 'center', gap: 4,
            background: '#f0fdf4', border: '1px solid #bbf7d0', color: '#065f46',
            padding: '5px 10px', borderRadius: 6, fontSize: 12, fontWeight: 600,
            cursor: 'pointer', fontFamily: 'inherit', flexShrink: 0,
          }}>
            👤 {pmLabel || 'הגדר PM'} <span style={{ fontSize: 11, color: '#6b7280' }}>✎</span>
          </button>
          <button onClick={onOpenClient} style={{
            background: '#fff', border: '1px solid var(--v1-border)', color: 'var(--v1-ink)',
            padding: '7px 12px', borderRadius: 6, fontSize: 13, cursor: 'pointer',
            fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 5,
          }}>
            <Icon name="users" size={14}/> לקוח
          </button>
          <button onClick={onNewDaily} style={{
            background: 'var(--v1-accent)', color: '#fff', border: 'none',
            padding: '7px 14px', borderRadius: 6, fontSize: 13, fontWeight: 700, cursor: 'pointer',
            display: 'flex', alignItems: 'center', gap: 5, fontFamily: 'inherit',
          }}>
            <Icon name="plus" size={14}/> עדכון חדש
          </button>
        </>
      }
    >
      {/* KPI summary strip */}
      <div style={{ padding: isMobile ? '12px 14px 0' : '20px 28px 0', background: '#fff', borderBottom: '1px solid var(--v1-border)' }}>
        {/* Mobile quick actions — portrait only */}
        {isMobile && !isLandscape && (
          <div style={{ display: 'flex', gap: 8, marginBottom: 12 }}>
            <button onClick={onOpenReports} style={{
              flex: 1, padding: '10px', borderRadius: 9, border: 'none',
              background: '#1a2c4a', color: '#fff', fontFamily: 'Assistant, sans-serif',
              fontSize: 14, fontWeight: 700, cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
            }}>📈 כל הדוחות</button>
            <button onClick={onNewDaily} style={{
              flex: 1, padding: '10px', borderRadius: 9, border: 'none',
              background: '#1d4ed8', color: '#fff', fontFamily: 'Assistant, sans-serif',
              fontSize: 14, fontWeight: 700, cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
            }}>📝 דוח חדש</button>
          </div>
        )}
        <div style={{ display: 'grid', gridTemplateColumns: !isMobile ? 'repeat(5, 1fr)' : isLandscape ? 'repeat(5, 1fr)' : '1fr 1fr', gap: isMobile ? (isLandscape ? 10 : 10) : 20, paddingBottom: isMobile ? 10 : 20 }}>
          <div onClick={onOpenGantt} style={{ cursor: 'pointer', borderRadius: 6, padding: '4px 6px', margin: '-4px -6px' }}
            onMouseEnter={e => e.currentTarget.style.background='#f8fafc'}
            onMouseLeave={e => e.currentTarget.style.background='transparent'}>
            <div style={{ fontSize: 11, color: 'var(--v1-ink-soft)', fontWeight: 500, textTransform: 'uppercase', letterSpacing: 0.3 }}>התקדמות <span style={{color:'var(--v1-accent)'}}>›</span></div>
            <div style={{ fontSize: isMobile ? 22 : 26, fontWeight: 700, marginTop: 4 }}>{project.progress}%</div>
            <V1ProgressBar value={project.progress} status={project.status}/>
          </div>
          <div onClick={onOpenBudget} style={{ cursor: 'pointer', borderRadius: 6, padding: '4px 6px', margin: '-4px -6px' }}
            onMouseEnter={e => e.currentTarget.style.background='#f8fafc'}
            onMouseLeave={e => e.currentTarget.style.background='transparent'}>
            <div style={{ fontSize: 11, color: 'var(--v1-ink-soft)', fontWeight: 500, textTransform: 'uppercase', letterSpacing: 0.3 }}>תקציב <span style={{color:'var(--v1-accent)'}}>›</span></div>
            <div style={{ fontSize: isMobile ? 16 : 26, fontWeight: 700, marginTop: 4 }}>{fmtMoney(project.spent)}</div>
            <div style={{ fontSize: 12, color: 'var(--v1-ink-soft)' }}>{project.budget > 0 ? Math.round(project.spent/project.budget*100) : 0}% מתוך {fmtMoney(project.budget)}</div>
          </div>
          <div>
            <div style={{ fontSize: 11, color: 'var(--v1-ink-soft)', fontWeight: 500, textTransform: 'uppercase', letterSpacing: 0.3 }}>ימים שנותרו</div>
            <div style={{ fontSize: isMobile ? 22 : 26, fontWeight: 700, marginTop: 4 }}>{project.daysLeft}</div>
            <div style={{ fontSize: 12, color: 'var(--v1-ink-soft)' }}>סיום: {project.endDate}</div>
          </div>
          <div onClick={onOpenTasks} style={{ cursor: 'pointer', borderRadius: 6, padding: '4px 6px', margin: '-4px -6px' }}
            onMouseEnter={e => e.currentTarget.style.background='#f8fafc'}
            onMouseLeave={e => e.currentTarget.style.background='transparent'}>
            <div style={{ fontSize: 11, color: 'var(--v1-ink-soft)', fontWeight: 500, textTransform: 'uppercase', letterSpacing: 0.3 }}>צוות <span style={{color:'var(--v1-accent)'}}>›</span></div>
            <div style={{ fontSize: 26, fontWeight: 700, marginTop: 4 }}>{project.team}</div>
            <div style={{ fontSize: 12, color: 'var(--v1-ink-soft)' }}>{detail.contractors.length} קבלני משנה</div>
          </div>
          <div>
            <div style={{ fontSize: 11, color: 'var(--v1-ink-soft)', fontWeight: 500, textTransform: 'uppercase', letterSpacing: 0.3 }}>אבן דרך הבאה</div>
            <div style={{ fontSize: 15, fontWeight: 700, marginTop: 6, lineHeight: 1.3 }}>{project.nextMilestone}</div>
            <div style={{ fontSize: 12, color: 'var(--v1-ink-soft)', marginTop: 2 }}>{project.nextMilestoneDate}</div>
          </div>
        </div>
      </div>

      {/* Sub-view content */}
      <div style={{ padding: isMobile ? '14px' : '24px 28px' }}>
        {subView === 'overview' && <OverviewTab project={project} detail={detail} onOpenReports={onOpenReports} onNewDaily={onNewDaily} onOpenBooklet={onOpenBooklet} projectId={projectId}/>}
        {subView === 'tasks'    && <TasksBoard tasks={detail.tasks} onOpenTasks={onOpenTasks}/>}
        {subView === 'updates'  && <UpdatesFeed updates={detail.updates} onOpenReports={onOpenReports}/>}
        {subView === 'docs'     && <DocsGrid docs={detail.documents}/>}
        {subView === 'team'     && <TeamList contractors={detail.contractors}/>}
      </div>
    </V1Shell>
    </>
  );
};

// ── V1Shell — wraps AppShell ──────────────────────────────────────────────────
function V1Shell({ children, active, onNav, onBack, title, subtitle, actions, projectNav, activeSubView }) {
  if (typeof AppShell !== 'undefined') {
    return (
      <AppShell
        active={active}
        onNav={onNav}
        onBack={onBack}
        title={title}
        subtitle={subtitle}
        actions={actions}
        projectNav={projectNav}
        activeSubView={activeSubView}
      >
        {children}
      </AppShell>
    );
  }
  // fallback
  return (
    <div style={{ minHeight: '100%', background: 'var(--v1-bg)', fontFamily: 'Assistant, sans-serif', direction: 'rtl' }}>
      <header style={{ background: '#fff', borderBottom: '1px solid var(--v1-border)', padding: '14px 24px', display: 'flex', alignItems: 'center', gap: 12 }}>
        {onBack && <button onClick={onBack} style={{ background: 'transparent', border: 'none', cursor: 'pointer', color: '#6b7280', fontSize: 14 }}>← חזרה</button>}
        <div style={{ flex: 1 }}>
          {title && <div style={{ fontSize: 17, fontWeight: 700 }}>{title}</div>}
          {subtitle && <div style={{ fontSize: 12, color: '#6b7280' }}>{subtitle}</div>}
        </div>
        {actions}
      </header>
      {children}
    </div>
  );
}

// ── Overview ──────────────────────────────────────────────────────────────────
const OverviewTab = ({ project, detail, onOpenReports, onNewDaily, onOpenBooklet, projectId }) => {
  const { isMobile } = useViewport();
  const bookletData = React.useMemo(() => {
    try {
      const raw = localStorage.getItem('ybp_booklet_' + projectId);
      if (!raw) return { total: 17, done: 0 };
      const saved = JSON.parse(raw);
      const done = Object.values(saved).filter(v => v.completed).length;
      return { total: 17, done };
    } catch { return { total: 17, done: 0 }; }
  }, [projectId]);
  const bookletPct = Math.round(bookletData.done / bookletData.total * 100);

  return (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
    <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1.5fr 1fr', gap: 16 }}>
    <div style={{ background: '#fff', border: '1px solid var(--v1-border)', borderRadius: 10, padding: isMobile ? 14 : 20 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 14 }}>
        <h3 style={{ margin: 0, fontSize: 15, fontWeight: 700 }}>שלבי הפרויקט</h3>
        <span style={{ fontSize: 12, color: 'var(--v1-ink-soft)' }}>{project.phases.filter(p => p.status === 'done').length}/{project.phases.length}</span>
      </div>
      {project.phases.map((ph, i) => (
        <div key={i} style={{
          display: 'grid', gridTemplateColumns: isMobile ? '28px 1fr 60px' : '32px 1fr 80px 48px',
          gap: isMobile ? 8 : 12, alignItems: 'center', padding: '10px 0',
          borderTop: i > 0 ? '1px solid var(--v1-border)' : 'none',
        }}>
          <div style={{
            width: 28, height: 28, borderRadius: 14,
            background: ph.status === 'done' ? '#10b981' : ph.status === 'active' ? '#3b82f6' : '#e5e7eb',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: '#fff', fontSize: 12, fontWeight: 700,
          }}>
            {ph.status === 'done' ? <Icon name="check" size={14} color="#fff" strokeWidth={3}/> : i + 1}
          </div>
          <div style={{ fontSize: isMobile ? 13 : 13.5, fontWeight: ph.status === 'active' ? 600 : 500 }}>{ph.name}</div>
          <V1ProgressBar value={ph.progress} status={ph.status === 'done' ? 'done' : 'active'}/>
          {!isMobile && <V1StatusChip
            status={ph.status === 'done' ? 'done' : ph.status === 'active' ? 'active' : 'delay'}
            label={ph.status === 'done' ? 'הושלם' : ph.status === 'active' ? 'בביצוע' : 'בהמתנה'}
          />}
        </div>
      ))}
    </div>

    <div style={{ background: '#fff', border: '1px solid var(--v1-border)', borderRadius: 10, padding: isMobile ? 14 : 20 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 14 }}>
        <h3 style={{ margin: 0, fontSize: 15, fontWeight: 700 }}>פעילות אחרונה</h3>
        <button onClick={onOpenReports} style={{ background: 'transparent', border: 'none', color: 'var(--v1-accent)', fontSize: 12, cursor: 'pointer', fontFamily: 'inherit' }}>הכל ›</button>
      </div>
      {detail.updates.slice(0, 5).map(u => {
        const dotColor = u.type === 'alert' ? '#ef4444' : u.type === 'milestone' ? '#8b5cf6' : u.type === 'progress' ? '#3b82f6' : '#94a3b8';
        return (
          <div key={u.id} style={{ display: 'flex', gap: 10, padding: '10px 0', borderTop: '1px solid var(--v1-border)' }}>
            <div style={{ width: 8, height: 8, borderRadius: 4, background: dotColor, marginTop: 6, flexShrink: 0 }}/>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12.5, color: 'var(--v1-ink)', lineHeight: 1.4 }}>{u.text}</div>
              <div style={{ fontSize: 11, color: 'var(--v1-ink-soft)', marginTop: 3 }}>
                {u.author} • {u.team} • {u.time}
              </div>
            </div>
          </div>
        );
      })}
    </div>
    </div>

    {/* כרטיס חוברת פרויקט */}
    {onOpenBooklet && (
      <div onClick={onOpenBooklet} style={{
        background: '#fff', border: '1px solid var(--v1-border)', borderRadius: 10,
        padding: '18px 22px', cursor: 'pointer', transition: 'all 0.15s',
        display: 'flex', alignItems: 'center', gap: 18,
      }}
      onMouseEnter={e => { e.currentTarget.style.boxShadow = '0 4px 16px rgba(0,0,0,0.07)'; e.currentTarget.style.borderColor = '#1a2c4a'; }}
      onMouseLeave={e => { e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.borderColor = 'var(--v1-border)'; }}>
        {/* Progress ring */}
        <div style={{ position: 'relative', width: 60, height: 60, flexShrink: 0 }}>
          <svg width="60" height="60" style={{ transform: 'rotate(-90deg)' }}>
            <circle cx="30" cy="30" r="24" fill="none" stroke="#f1f5f9" strokeWidth="6"/>
            <circle cx="30" cy="30" r="24" fill="none" stroke="#1a2c4a" strokeWidth="6"
              strokeDasharray={`${2 * Math.PI * 24}`}
              strokeDashoffset={`${2 * Math.PI * 24 * (1 - bookletPct / 100)}`}
              strokeLinecap="round"/>
          </svg>
          <div style={{
            position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 13, fontWeight: 800, color: '#1a2c4a',
          }}>{bookletPct}%</div>
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 16, fontWeight: 700, color: '#1a2c4a', marginBottom: 4 }}>📋 חוברת פרויקט</div>
          <div style={{ fontSize: 13, color: 'var(--v1-ink-soft)' }}>
            {bookletData.done} מתוך {bookletData.total} משימות הושלמו
          </div>
          <div style={{ marginTop: 8, height: 5, background: '#f1f5f9', borderRadius: 3, overflow: 'hidden' }}>
            <div style={{ height: '100%', width: `${bookletPct}%`, background: '#1a2c4a', borderRadius: 3, transition: 'width 0.4s' }}/>
          </div>
        </div>
        <div style={{ fontSize: 20, color: '#9ca3af' }}>›</div>
      </div>
    )}
  </div>
  );
};

// ── Tasks Board ───────────────────────────────────────────────────────────────
const TasksBoard = ({ tasks, onOpenTasks }) => {
  const { isMobile } = useViewport();
  const cols = [
    { k: 'todo',        label: 'לביצוע',  color: '#94a3b8' },
    { k: 'in-progress', label: 'בביצוע',  color: '#3b82f6' },
    { k: 'review',      label: 'בבדיקה',  color: '#f59e0b' },
    { k: 'blocked',     label: 'חסום',    color: '#ef4444' },
    { k: 'done',        label: 'הושלם',   color: '#10b981' },
  ];
  return (
    <div style={{ overflowX: isMobile ? 'auto' : 'visible', marginInline: isMobile ? -14 : 0, paddingInline: isMobile ? 14 : 0 }}>
    <div style={{ display: 'grid', gridTemplateColumns: isMobile ? 'repeat(5, 220px)' : 'repeat(5, 1fr)', gap: 10, minWidth: isMobile ? 1130 : 'auto' }}>
      {cols.map(col => {
        const items = tasks.filter(t => t.status === col.k);
        return (
          <div key={col.k} style={{ background: '#fafbfc', border: '1px solid var(--v1-border)', borderRadius: 10, padding: 10, minHeight: isMobile ? 300 : 400 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12, paddingInline: 4 }}>
              <span style={{ width: 8, height: 8, borderRadius: 4, background: col.color }}/>
              <span style={{ fontSize: 12.5, fontWeight: 700 }}>{col.label}</span>
              <span style={{ fontSize: 11, color: 'var(--v1-ink-soft)' }}>{items.length}</span>
            </div>
            {items.map(t => {
              const prColor = t.priority === 'דחוף' ? '#ef4444' : t.priority === 'גבוהה' ? '#f59e0b' : t.priority === 'בינונית' ? '#3b82f6' : '#94a3b8';
              return (
                <div key={t.id} onClick={() => onOpenTasks && onOpenTasks()} style={{
                  background: '#fff', border: '1px solid var(--v1-border)', borderRadius: 8,
                  padding: 12, marginBottom: 8, cursor: 'pointer', transition: 'box-shadow 0.15s',
                }}
                onMouseEnter={e => e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.06)'}
                onMouseLeave={e => e.currentTarget.style.boxShadow = 'none'}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
                    <span style={{ background: `${prColor}15`, color: prColor, fontSize: 10.5, fontWeight: 600, padding: '2px 7px', borderRadius: 4 }}>{t.priority}</span>
                    <span style={{ fontSize: 10.5, color: 'var(--v1-ink-soft)' }}>{t.phase}</span>
                  </div>
                  <div style={{ fontSize: 13, fontWeight: 500, lineHeight: 1.35, marginBottom: 10 }}>{t.title}</div>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                    <Avatar name={t.assignee} size={22}/>
                    <div style={{ fontSize: 11, color: 'var(--v1-ink-soft)', display: 'flex', alignItems: 'center', gap: 4 }}>
                      <Icon name="calendar" size={11}/>{t.due.slice(5)}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        );
      })}
    </div>
    </div>
  );
};

// ── Updates Feed ──────────────────────────────────────────────────────────────
const UpdatesFeed = ({ updates, onOpenReports }) => (
  <div style={{ maxWidth: 760, margin: '0 auto' }}>
    {updates.map(u => {
      const colors = {
        alert:     { bg: '#fef2f2', fg: '#b91c1c', label: 'התראה' },
        milestone: { bg: '#f5f3ff', fg: '#6d28d9', label: 'אבן דרך' },
        progress:  { bg: '#eff6ff', fg: '#1d4ed8', label: 'התקדמות' },
        info:      { bg: '#f1f5f9', fg: '#475569', label: 'מידע' },
      }[u.type] || {};
      return (
        <div key={u.id} onClick={() => onOpenReports && onOpenReports()} style={{
          background: '#fff', border: '1px solid var(--v1-border)', borderRadius: 10,
          padding: 18, marginBottom: 12, cursor: 'pointer', transition: 'box-shadow 0.15s',
        }}
        onMouseEnter={e => e.currentTarget.style.boxShadow='0 2px 8px rgba(0,0,0,0.06)'}
        onMouseLeave={e => e.currentTarget.style.boxShadow='none'}>
          <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
            <Avatar name={u.author} size={38}/>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6, flexWrap: 'wrap' }}>
                <span style={{ fontWeight: 600, fontSize: 13.5 }}>{u.author}</span>
                <span style={{ fontSize: 11.5, color: 'var(--v1-ink-soft)' }}>{u.team}</span>
                <span style={{ fontSize: 11.5, color: 'var(--v1-ink-soft)' }}>•</span>
                <span style={{ fontSize: 11.5, color: 'var(--v1-ink-soft)' }}>{u.time}</span>
                <span style={{ marginRight: 'auto', background: colors.bg, color: colors.fg, fontSize: 11, fontWeight: 600, padding: '2px 8px', borderRadius: 4 }}>{colors.label}</span>
              </div>
              <div style={{ fontSize: 14, lineHeight: 1.5 }}>{u.text}</div>
              {u.photos > 0 && (
                <div style={{ display: 'flex', gap: 6, marginTop: 12 }}>
                  {[...Array(Math.min(u.photos, 4))].map((_, i) => (
                    <ProjectPlaceholder key={i} kind="restaurant" style={{ width: 80, height: 60, borderRadius: 6 }}/>
                  ))}
                  {u.photos > 4 && (
                    <div style={{ width: 80, height: 60, borderRadius: 6, background: '#f1f5f9', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, fontWeight: 600, color: 'var(--v1-ink-soft)' }}>+{u.photos - 4}</div>
                  )}
                </div>
              )}
            </div>
          </div>
        </div>
      );
    })}
  </div>
);

// ── Docs Grid ─────────────────────────────────────────────────────────────────
const DocsGrid = ({ docs }) => {
  const { isMobile } = useViewport();
  return (
  <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(3, 1fr)', gap: isMobile ? 10 : 14 }}>
    {docs.map(d => (
      <div key={d.id} style={{
        background: '#fff', border: '1px solid var(--v1-border)', borderRadius: 10,
        padding: 16, cursor: 'pointer', display: 'flex', gap: 12, alignItems: 'flex-start',
      }}>
        <div style={{
          width: 42, height: 52, borderRadius: 6, flexShrink: 0,
          background: d.type === 'pdf' ? '#fef2f2' : d.type === 'folder' ? '#fffbeb' : '#ecfdf5',
          color: d.type === 'pdf' ? '#b91c1c' : d.type === 'folder' ? '#b45309' : '#047857',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 10, fontWeight: 700,
        }}>
          {d.type === 'folder' ? <Icon name="folder" size={22}/> : d.type.toUpperCase()}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13.5, fontWeight: 600, lineHeight: 1.3, marginBottom: 4 }}>{d.name}</div>
          <div style={{ fontSize: 11.5, color: 'var(--v1-ink-soft)', marginBottom: 2 }}>{d.author}</div>
          <div style={{ fontSize: 11, color: 'var(--v1-ink-soft)' }}>{d.size} • עודכן {d.updated.slice(5)}</div>
        </div>
        <Icon name="download" size={14} color="var(--v1-ink-soft)"/>
      </div>
    ))}
  </div>
  );
};

// ── Team List ─────────────────────────────────────────────────────────────────
const TeamList = ({ contractors }) => {
  const { isMobile } = useViewport();
  return (
  <div style={{ background: '#fff', border: '1px solid var(--v1-border)', borderRadius: 10, overflow: 'hidden' }}>
    {contractors.map((c, i) => isMobile ? (
      <div key={i} style={{
        padding: '14px 16px',
        borderBottom: i < contractors.length - 1 ? '1px solid var(--v1-border)' : 'none',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8 }}>
          <Avatar name={c.contact} size={38}/>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 14, fontWeight: 700, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c.name}</div>
            <div style={{ fontSize: 12, color: 'var(--v1-ink-soft)', marginTop: 2 }}>{c.role}</div>
          </div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
            <Icon name="star" size={13} color="#f59e0b"/>
            <span style={{ fontSize: 13, fontWeight: 700 }}>{c.rating}</span>
          </div>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 13, color: 'var(--v1-ink-soft)' }}>
          <Icon name="phone" size={13}/>{c.phone}
          <span style={{ marginRight: 8 }}>{c.contact}</span>
        </div>
      </div>
    ) : (
      <div key={i} style={{
        display: 'grid', gridTemplateColumns: '44px 1.5fr 1fr 1fr 0.7fr auto', gap: 16,
        padding: '16px 20px',
        borderBottom: i < contractors.length - 1 ? '1px solid var(--v1-border)' : 'none',
        alignItems: 'center',
      }}>
        <Avatar name={c.contact} size={40}/>
        <div>
          <div style={{ fontSize: 13.5, fontWeight: 600 }}>{c.name}</div>
          <div style={{ fontSize: 11.5, color: 'var(--v1-ink-soft)', marginTop: 2 }}>{c.role}</div>
        </div>
        <div>
          <div style={{ fontSize: 13 }}>{c.contact}</div>
          <div style={{ fontSize: 11.5, color: 'var(--v1-ink-soft)' }}>איש קשר</div>
        </div>
        <div style={{ fontSize: 13, display: 'flex', alignItems: 'center', gap: 6 }}>
          <Icon name="phone" size={12} color="var(--v1-ink-soft)"/>{c.phone}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          <Icon name="star" size={13} color="#f59e0b"/>
          <span style={{ fontSize: 13, fontWeight: 600 }}>{c.rating}</span>
        </div>
        <button style={{
          background: '#fff', border: '1px solid var(--v1-border)',
          padding: '6px 12px', borderRadius: 6, fontSize: 12, cursor: 'pointer', fontFamily: 'inherit',
        }}>פרטים</button>
      </div>
    ))}
  </div>
  );
};

// ── V1ProjectsList — עטוף ב-AppShell ─────────────────────────────────────────
const V1ProjectsList = ({ onOpenProject, onNewProject, onNav }) => {
  const projects = YBP_DATA.projects;

  return (
    <V1Shell active="list" onNav={onNav} title="פרויקטים">
      <div style={{ padding: '24px 28px', background: 'var(--v1-bg, #f6f7f9)', minHeight: '100%' }}>
        {/* Header row */}
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 20 }}>
          <h2 style={{ margin: 0, fontSize: 22, fontWeight: 700, color: 'var(--v1-ink)' }}>כל הפרויקטים</h2>
          <button onClick={onNewProject} style={{
            background: 'var(--v1-accent)', color: '#fff', border: 'none',
            padding: '9px 18px', borderRadius: 8, fontSize: 14, fontWeight: 700,
            cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 6,
          }}>
            <Icon name="plus" size={15}/> פרויקט חדש
          </button>
        </div>

        {/* Projects grid */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(320px, 1fr))', gap: 16 }}>
          {projects.map(p => {
            const statusColors = {
              active:    { bg: '#eff6ff', fg: '#1d4ed8', label: 'פעיל' },
              done:      { bg: '#f0fdf4', fg: '#16a34a', label: 'הושלם' },
              delay:     { bg: '#fef2f2', fg: '#dc2626', label: 'עיכוב' },
              attention: { bg: '#fffbeb', fg: '#d97706', label: 'דרוש טיפול' },
            };
            const sc = statusColors[p.status] || statusColors.active;
            return (
              <div key={p.id} onClick={() => onOpenProject(p.id)} style={{
                background: '#fff', border: '1px solid var(--v1-border)', borderRadius: 12,
                padding: 20, cursor: 'pointer', transition: 'all 0.15s',
              }}
              onMouseEnter={e => { e.currentTarget.style.boxShadow = '0 4px 16px rgba(0,0,0,0.08)'; e.currentTarget.style.transform = 'translateY(-1px)'; }}
              onMouseLeave={e => { e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.transform = 'none'; }}>
                <div style={{ display: 'flex', gap: 14, alignItems: 'flex-start', marginBottom: 16 }}>
                  <ProjectPlaceholder kind={p.cover} style={{ width: 56, height: 56, borderRadius: 8, flexShrink: 0 }}/>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
                      <span style={{ background: sc.bg, color: sc.fg, fontSize: 11, fontWeight: 600, padding: '2px 8px', borderRadius: 4 }}>{sc.label}</span>
                    </div>
                    <div style={{ fontSize: 16, fontWeight: 700, color: 'var(--v1-ink)', lineHeight: 1.3 }}>{p.name}</div>
                    <div style={{ fontSize: 12, color: 'var(--v1-ink-soft)', marginTop: 2 }}>{p.client}</div>
                  </div>
                </div>
                <V1ProgressBar value={p.progress} status={p.status}/>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 10, marginTop: 14 }}>
                  <div>
                    <div style={{ fontSize: 10, color: 'var(--v1-ink-soft)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.3 }}>תקציב</div>
                    <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--v1-ink)', marginTop: 3 }}>{fmtMoney(p.budget)}</div>
                  </div>
                  <div>
                    <div style={{ fontSize: 10, color: 'var(--v1-ink-soft)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.3 }}>ימים</div>
                    <div style={{ fontSize: 14, fontWeight: 700, color: p.daysLeft < 14 ? '#dc2626' : 'var(--v1-ink)', marginTop: 3 }}>{p.daysLeft}</div>
                  </div>
                  <div>
                    <div style={{ fontSize: 10, color: 'var(--v1-ink-soft)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.3 }}>צוות</div>
                    <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--v1-ink)', marginTop: 3 }}>{p.team}</div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </V1Shell>
  );
};

// ── Helper components ─────────────────────────────────────────────────────────
const V1ProgressBar = ({ value, status }) => {
  const color = status === 'done' ? '#10b981' : status === 'delay' ? '#ef4444' : status === 'attention' ? '#f59e0b' : '#3b82f6';
  return (
    <div style={{ height: 5, background: '#e5e7eb', borderRadius: 3, overflow: 'hidden', marginTop: 6 }}>
      <div style={{ height: '100%', width: `${value}%`, background: color, borderRadius: 3, transition: 'width 0.4s' }}/>
    </div>
  );
};

const V1StatusChip = ({ status, label }) => {
  const colors = {
    done:      { bg: '#f0fdf4', fg: '#16a34a' },
    active:    { bg: '#eff6ff', fg: '#1d4ed8' },
    delay:     { bg: '#fef2f2', fg: '#dc2626' },
    attention: { bg: '#fffbeb', fg: '#d97706' },
  };
  const c = colors[status] || colors.active;
  return (
    <span style={{ display: 'inline-block', background: c.bg, color: c.fg, fontSize: 11, fontWeight: 600, padding: '3px 8px', borderRadius: 4, whiteSpace: 'nowrap' }}>
      {label}
    </span>
  );
};

window.V1ProjectDetail = V1ProjectDetail;
window.V1ProjectsList  = V1ProjectsList;
window.V1Shell         = V1Shell;
window.V1ProgressBar   = V1ProgressBar;
window.V1StatusChip    = V1StatusChip;
})();
