/**
 * Dashboard Module — לוח בקרה
 * PMDashboard: KPI cards + Bar Chart + Pie Chart + Funnel + Action Items
 * ClientDashboard: פרוגרס + אבן דרך
 * ContractorDashboard: ריג'קטים + מכרזים + תשלומים
 * שומר ב-SyncStore (אין state נוסף — הכל נגזר מנתונים קיימים)
 */
(function () {

const { useState, useMemo } = React;

// ── Design tokens ─────────────────────────────────────────────────────────────
const NAVY  = '#1a2c4a';
const GOLD  = '#b5a882';
const GREEN = '#16a34a';
const RED   = '#dc2626';
const BLUE  = '#2563eb';
const AMBER = '#eab308';
const GRAY  = '#6b7280';

// ── Helpers ───────────────────────────────────────────────────────────────────
function fmtNum(n) {
  if (n >= 1000000) return (n/1000000).toFixed(1) + 'M';
  if (n >= 1000)    return Math.round(n/1000) + 'K';
  return String(n);
}
function fmtMoneySh(n) {
  if (n >= 1000000) return (n/1000000).toFixed(1) + 'M ₪';
  if (n >= 1000)    return Math.round(n/1000) + 'K ₪';
  return n + ' ₪';
}
function pct(a, b) { return b > 0 ? Math.round(a/b*100) : 0; }

// ── KPI Card ──────────────────────────────────────────────────────────────────
const KpiCard = ({ label, value, sub, color, icon, onClick }) => (
  <div onClick={onClick} style={{
    background: 'var(--ybp-panel,#fff)',
    border: '1px solid var(--ybp-border,#e5e7eb)',
    borderRadius: 12, padding: '16px 18px',
    display: 'flex', flexDirection: 'column', gap: 6,
    cursor: onClick ? 'pointer' : 'default',
    transition: 'box-shadow 0.15s',
    flex: 1, minWidth: 130,
  }}
    onMouseEnter={e => onClick && (e.currentTarget.style.boxShadow = '0 4px 12px rgba(0,0,0,0.08)')}
    onMouseLeave={e => e.currentTarget.style.boxShadow = 'none'}
  >
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
      <span style={{ fontSize: 22 }}>{icon}</span>
      {sub && <span style={{ fontSize: 11, color: GRAY, fontWeight: 500 }}>{sub}</span>}
    </div>
    <div style={{ fontSize: 28, fontWeight: 800, color: color || NAVY, letterSpacing: -0.5, lineHeight: 1 }}>
      {value}
    </div>
    <div style={{ fontSize: 12, color: GRAY, fontWeight: 500 }}>{label}</div>
  </div>
);

// ── Bar Chart (SVG) ───────────────────────────────────────────────────────────
const BarChart = ({ data, title, color = NAVY, height = 160 }) => {
  const max = Math.max(...data.map(d => d.value), 1);
  const barW = Math.floor(220 / data.length) - 8;

  return (
    <div style={{ background: 'var(--ybp-panel,#fff)', borderRadius: 12, padding: 16, border: '1px solid var(--ybp-border,#e5e7eb)' }}>
      <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--ybp-ink,#111827)', marginBottom: 12 }}>{title}</div>
      <svg width="100%" height={height} viewBox={`0 0 ${data.length * (barW+8) + 20} ${height}`} style={{ overflow: 'visible' }}>
        {data.map((d, i) => {
          const barH = Math.round((d.value / max) * (height - 36));
          const x = 10 + i * (barW + 8);
          const y = height - 26 - barH;
          return (
            <g key={i}>
              <rect x={x} y={y} width={barW} height={barH}
                fill={d.color || color} rx={4} opacity={0.9} />
              <text x={x + barW/2} y={height - 12} textAnchor="middle"
                fontSize={10} fill={GRAY} fontFamily="Assistant,sans-serif">
                {d.label}
              </text>
              {d.value > 0 && (
                <text x={x + barW/2} y={y - 4} textAnchor="middle"
                  fontSize={10} fontWeight="700" fill={d.color || color} fontFamily="Assistant,sans-serif">
                  {d.value}
                </text>
              )}
            </g>
          );
        })}
      </svg>
    </div>
  );
};

// ── Pie / Donut Chart (SVG) ───────────────────────────────────────────────────
const PieChart = ({ data, title, total, totalLabel }) => {
  const r = 52, cx = 70, cy = 65;
  let cumAngle = -Math.PI / 2;
  const totalVal = data.reduce((s, d) => s + d.value, 0) || 1;

  const slices = data.map(d => {
    const angle = (d.value / totalVal) * 2 * Math.PI;
    const x1 = cx + r * Math.cos(cumAngle);
    const y1 = cy + r * Math.sin(cumAngle);
    cumAngle += angle;
    const x2 = cx + r * Math.cos(cumAngle);
    const y2 = cy + r * Math.sin(cumAngle);
    const large = angle > Math.PI ? 1 : 0;
    return { ...d, path: `M${cx},${cy} L${x1},${y1} A${r},${r} 0 ${large},1 ${x2},${y2} Z` };
  });

  return (
    <div style={{ background: 'var(--ybp-panel,#fff)', borderRadius: 12, padding: 16, border: '1px solid var(--ybp-border,#e5e7eb)' }}>
      <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--ybp-ink,#111827)', marginBottom: 8 }}>{title}</div>
      <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
        <svg width={140} height={130}>
          {slices.map((s, i) => (
            <path key={i} d={s.path} fill={s.color} opacity={0.9} />
          ))}
          {/* Inner circle for donut */}
          <circle cx={cx} cy={cy} r={28} fill="var(--ybp-panel,#fff)" />
          {total !== undefined && (
            <>
              <text x={cx} y={cy} textAnchor="middle" dominantBaseline="middle"
                fontSize={16} fontWeight="800" fill={NAVY} fontFamily="Assistant,sans-serif">
                {typeof total === 'number' ? fmtMoneySh(total) : total}
              </text>
              {totalLabel && (
                <text x={cx} y={cy + 16} textAnchor="middle"
                  fontSize={9} fill={GRAY} fontFamily="Assistant,sans-serif">
                  {totalLabel}
                </text>
              )}
            </>
          )}
        </svg>
        {/* Legend */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6, flex: 1 }}>
          {data.map((d, i) => (
            <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <div style={{ width: 10, height: 10, borderRadius: 2, background: d.color, flexShrink: 0 }} />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--ybp-ink,#111827)' }}>{d.label}</div>
                <div style={{ fontSize: 11, color: GRAY }}>
                  {typeof d.value === 'number' && d.value > 1000 ? fmtMoneySh(d.value) : d.value}
                  {' '}({pct(d.value, totalVal)}%)
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

// ── Horizontal Bar (top projects by delay) ────────────────────────────────────
const HorizontalBar = ({ data, title }) => {
  const max = Math.max(...data.map(d => d.value), 1);
  return (
    <div style={{ background: 'var(--ybp-panel,#fff)', borderRadius: 12, padding: 16, border: '1px solid var(--ybp-border,#e5e7eb)' }}>
      <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--ybp-ink,#111827)', marginBottom: 12 }}>{title}</div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {data.map((d, i) => (
          <div key={i}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
              <span style={{ fontSize: 12, color: 'var(--ybp-ink,#111827)', fontWeight: 500,
                maxWidth: 160, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                {d.label}
              </span>
              <span style={{ fontSize: 12, fontWeight: 700, color: d.value > 14 ? RED : d.value > 7 ? AMBER : GREEN }}>
                {d.value > 0 ? `+${d.value} ימים` : 'בזמן'}
              </span>
            </div>
            <div style={{ height: 8, borderRadius: 4, background: 'var(--ybp-border,#e5e7eb)', overflow: 'hidden' }}>
              <div style={{
                height: '100%', borderRadius: 4,
                width: `${pct(d.value, max)}%`,
                background: d.value > 14 ? RED : d.value > 7 ? AMBER : GREEN,
                transition: 'width 0.5s ease',
              }} />
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

// ── Action Items ──────────────────────────────────────────────────────────────
const ActionItems = ({ items, onNavigate }) => (
  <div style={{ background: 'var(--ybp-panel,#fff)', borderRadius: 12, padding: 16, border: '1px solid var(--ybp-border,#e5e7eb)' }}>
    <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--ybp-ink,#111827)', marginBottom: 10 }}>⚡ דורש טיפול</div>
    <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
      {items.length === 0 ? (
        <div style={{ fontSize: 13, color: GRAY, padding: '8px 0', textAlign: 'center' }}>✅ הכל מטופל!</div>
      ) : items.map((item, i) => (
        <div key={i} onClick={() => onNavigate && onNavigate(item.screen)}
          style={{
            display: 'flex', alignItems: 'center', gap: 10,
            padding: '10px 0',
            borderBottom: i < items.length - 1 ? '1px solid var(--ybp-border,#e5e7eb)' : 'none',
            cursor: item.screen ? 'pointer' : 'default',
          }}
          onMouseEnter={e => item.screen && (e.currentTarget.style.background = 'var(--ybp-row-hover,#f6f7f9)')}
          onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
        >
          <span style={{ fontSize: 18, flexShrink: 0 }}>{item.icon}</span>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ybp-ink,#111827)' }}>{item.title}</div>
            {item.sub && <div style={{ fontSize: 11, color: GRAY }}>{item.sub}</div>}
          </div>
          <span style={{
            padding: '2px 8px', borderRadius: 99, fontSize: 11, fontWeight: 700,
            background: item.urgency === 'high' ? '#fef2f2' : '#fffbeb',
            color: item.urgency === 'high' ? RED : AMBER,
            flexShrink: 0,
          }}>{item.badge}</span>
        </div>
      ))}
    </div>
  </div>
);

// ── PM Dashboard ──────────────────────────────────────────────────────────────
const PMDashboard = ({ onNavigate }) => {
  const data = window.YBP_DATA || { projects: [] };
  const projects = data.projects || [];
  const store = window.SyncStore ? window.SyncStore.get() : {};
  const tasks = (store.tasks || []).filter(t => t.status !== 'archived');
  const reports = store.reports || [];
  const tenders = store.tenders || [];
  const protocols = store.protocols || [];

  // ── KPIs ──
  const activeProjects = projects.filter(p => p.status !== 'הושלם' && p.status !== 'בוטל');
  const totalSpent = projects.reduce((s, p) => s + (p.spent || 0), 0);
  const openTasks = tasks.filter(t => t.status === 'open').length;
  const openTenders = tenders.filter(t => t.status === 'active' || t.status === 'bidding').length;

  // ── Bar: פרויקטים לפי שלב ──
  const stageMap = {};
  projects.forEach(p => {
    const stage = p.status || 'לא ידוע';
    stageMap[stage] = (stageMap[stage] || 0) + 1;
  });
  const stageColors = ['#1a2c4a','#2563eb','#16a34a','#eab308','#ea580c','#7c3aed'];
  const stageData = Object.entries(stageMap).map(([label, value], i) => ({
    label: label.length > 6 ? label.slice(0,6)+'…' : label,
    value,
    color: stageColors[i % stageColors.length],
  }));

  // ── Pie: ניצול תקציב ──
  const totalBudget = projects.reduce((s, p) => s + (p.budget || 0), 0);
  const budgetPie = [
    { label: 'הוצא', value: totalSpent, color: NAVY },
    { label: 'נותר', value: Math.max(totalBudget - totalSpent, 0), color: '#e5e7eb' },
  ];

  // ── Horizontal: עיכובים ──
  const delayData = projects
    .map(p => ({
      label: p.name,
      value: p.daysLeft < 0 ? Math.abs(p.daysLeft) : 0,
    }))
    .filter(d => d.value > 0)
    .sort((a, b) => b.value - a.value)
    .slice(0, 5);

  // ── דוחות שבוע אחרון ──
  const oneWeekAgo = Date.now() - 7 * 86400000;
  const recentReports = reports.filter(r => new Date(r.date || r.createdAt).getTime() > oneWeekAgo);
  const projectsNoReport = activeProjects.filter(p =>
    !recentReports.find(r => r.projectId === p.id)
  );

  // ── Action items ──
  const actionItems = [];
  if (openTasks > 0) actionItems.push({
    icon: '🔴', title: `${openTasks} משימות פתוחות`, sub: 'ריג\'קטים + ממצאים',
    badge: openTasks, urgency: openTasks > 5 ? 'high' : 'medium', screen: 'tasks',
  });
  if (projectsNoReport.length > 0) actionItems.push({
    icon: '📋', title: `${projectsNoReport.length} פרויקטים ללא דיווח השבוע`,
    sub: projectsNoReport.map(p => p.name).join(', '),
    badge: projectsNoReport.length, urgency: 'medium', screen: 'projectsNoReport',
  });
  if (openTenders > 0) actionItems.push({
    icon: '📬', title: `${openTenders} מכרזים פעילים`,
    sub: 'ממתינים לסיום הגשה',
    badge: openTenders, urgency: 'medium', screen: 'tenders',
  });

  const thisWeekMeetings = store.meetings
    ? store.meetings.filter(m => {
        const d = new Date(m.date || m.createdAt);
        const now = new Date();
        const startOfWeek = new Date(now.setDate(now.getDate() - now.getDay()));
        return d >= startOfWeek;
      }).length
    : 0;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16, padding: '16px', direction: 'rtl', fontFamily: 'Assistant, sans-serif' }}>

      {/* KPI Row */}
      <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
        <KpiCard icon="🏗" label="פרויקטים פעילים" value={activeProjects.length}
          sub={`מתוך ${projects.length}`} color={NAVY}
          onClick={() => onNavigate('list')} />
        <KpiCard icon="⚠️" label="ריג׳קטים פתוחים" value={openTasks}
          color={openTasks > 0 ? RED : GREEN}
          onClick={() => onNavigate('tasks')} />
        <KpiCard icon="📅" label="פגישות השבוע" value={thisWeekMeetings}
          color={AMBER} onClick={() => onNavigate('meetings')} />
      </div>

      {/* Charts row 1 */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 12 }}>
        {stageData.length > 0 && (
          <BarChart
            title="פרויקטים לפי שלב"
            data={stageData}
            height={150}
          />
        )}
      </div>

      {/* Charts row 2 */}
      {delayData.length > 0 && (
        <HorizontalBar
          title="🔴 פרויקטים בעיכוב (ימים)"
          data={delayData}
        />
      )}

      {/* Action items */}
      <ActionItems items={actionItems} onNavigate={onNavigate} />

      {/* Recent activity */}
      <div style={{ background: 'var(--ybp-panel,#fff)', borderRadius: 12, padding: 16, border: '1px solid var(--ybp-border,#e5e7eb)' }}>
        <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--ybp-ink,#111827)', marginBottom: 10 }}>📊 סטטיסטיקות</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
          {[
            { label: 'דוחות (30 יום)', value: reports.filter(r => new Date(r.date||r.createdAt) > new Date(Date.now()-30*86400000)).length, icon: '📋' },
            { label: 'פרוטוקולים', value: (store.protocols||[]).length, icon: '📝' },
            { label: 'מכרזים', value: tenders.length, icon: '📬' },
          ].map((s, i) => (
            <div key={i} style={{
              padding: '10px 12px', borderRadius: 8,
              background: 'var(--ybp-row-hover,#f6f7f9)',
              textAlign: 'center',
            }}>
              <div style={{ fontSize: 20 }}>{s.icon}</div>
              <div style={{ fontSize: 22, fontWeight: 800, color: NAVY }}>{s.value}</div>
              <div style={{ fontSize: 11, color: GRAY }}>{s.label}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

// ── Client Dashboard ──────────────────────────────────────────────────────────
const ClientDashboard = ({ projectId, onNavigate }) => {
  const data = window.YBP_DATA || { projects: [] };
  const projects = projectId
    ? data.projects.filter(p => p.id === projectId)
    : data.projects;
  const project = projects[0];

  if (!project) return (
    <EmptyState icon="folder" title="אין פרויקטים" description="אין פרויקטים מקושרים לחשבון שלך" />
  );

  const daysLeft = project.daysLeft || 0;
  const progressColor = project.progress >= 80 ? GREEN : project.progress >= 50 ? BLUE : AMBER;

  return (
    <div style={{ padding: 16, fontFamily: 'Assistant, sans-serif', direction: 'rtl', display: 'flex', flexDirection: 'column', gap: 14 }}>
      {/* Project card */}
      <div style={{ background: NAVY, borderRadius: 14, padding: 20, color: '#fff' }}>
        <div style={{ fontSize: 12, opacity: 0.7, marginBottom: 4 }}>הפרויקט שלך</div>
        <div style={{ fontSize: 20, fontWeight: 800, marginBottom: 4 }}>{project.name}</div>
        <div style={{ fontSize: 13, opacity: 0.8 }}>{project.location}</div>
        <div style={{ marginTop: 16 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 6 }}>
            <span style={{ fontSize: 13, opacity: 0.8 }}>התקדמות</span>
            <span style={{ fontSize: 18, fontWeight: 800 }}>{project.progress}%</span>
          </div>
          <div style={{ height: 8, borderRadius: 4, background: 'rgba(255,255,255,0.2)' }}>
            <div style={{ height: '100%', width: `${project.progress}%`, background: GOLD, borderRadius: 4, transition: 'width 0.5s' }} />
          </div>
        </div>
      </div>

      {/* KPIs */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        <div style={{ background: 'var(--ybp-panel,#fff)', borderRadius: 12, padding: 14, border: '1px solid var(--ybp-border,#e5e7eb)', textAlign: 'center' }}>
          <div style={{ fontSize: 28, fontWeight: 800, color: daysLeft < 30 ? RED : BLUE }}>{daysLeft}</div>
          <div style={{ fontSize: 12, color: GRAY }}>ימים לסיום</div>
          <div style={{ fontSize: 11, color: GRAY, marginTop: 2 }}>מסירה: {project.endDate}</div>
        </div>
        <div style={{ background: 'var(--ybp-panel,#fff)', borderRadius: 12, padding: 14, border: '1px solid var(--ybp-border,#e5e7eb)', textAlign: 'center' }}>
          <div style={{ fontSize: 28, fontWeight: 800, color: NAVY }}>{fmtMoneySh(project.budget)}</div>
          <div style={{ fontSize: 12, color: GRAY }}>תקציב</div>
          <div style={{ fontSize: 11, color: GRAY, marginTop: 2 }}>{pct(project.spent, project.budget)}% נוצל</div>
        </div>
      </div>

      {/* Quick links */}
      <div style={{ background: 'var(--ybp-panel,#fff)', borderRadius: 12, padding: 16, border: '1px solid var(--ybp-border,#e5e7eb)' }}>
        <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--ybp-ink,#111827)', marginBottom: 10 }}>גישה מהירה</div>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          {[
            { label: 'דוחות', icon: '📋', screen: 'reports' },
            { label: 'הצעות', icon: '📑', screen: 'quotes' },
            { label: 'תשלומים', icon: '💰', screen: 'payments' },
          ].map((l, i) => (
            <button key={i} onClick={() => onNavigate(l.screen)} style={{
              padding: '9px 16px', borderRadius: 8,
              background: 'var(--ybp-row-hover,#f6f7f9)',
              border: '1px solid var(--ybp-border,#e5e7eb)',
              fontSize: 13, fontWeight: 600, cursor: 'pointer',
              fontFamily: 'Assistant, sans-serif', color: 'var(--ybp-ink,#111827)',
              display: 'flex', alignItems: 'center', gap: 6,
            }}>{l.icon} {l.label}</button>
          ))}
        </div>
      </div>
    </div>
  );
};

// ── Contractor Dashboard ──────────────────────────────────────────────────────
const ContractorDashboard = ({ contractorName, onNavigate }) => {
  const store = window.SyncStore ? window.SyncStore.get() : {};
  const tasks = (store.tasks || []).filter(t =>
    t.status !== 'archived' && (!contractorName || t.assignee === contractorName)
  );
  const tenders = (store.tenders || []).filter(t =>
    t.status === 'active' || t.status === 'bidding'
  );

  const openTasks = tasks.filter(t => t.status === 'open');
  const inProgressTasks = tasks.filter(t => t.status === 'in-progress');
  const doneTasks = tasks.filter(t => t.status === 'done');

  const taskBarData = [
    { label: 'פתוח', value: openTasks.length, color: RED },
    { label: 'בטיפול', value: inProgressTasks.length, color: AMBER },
    { label: 'בוצע', value: doneTasks.length, color: GREEN },
  ];

  return (
    <div style={{ padding: 16, fontFamily: 'Assistant, sans-serif', direction: 'rtl', display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div style={{
        background: NAVY, borderRadius: 14, padding: '16px 20px', color: '#fff',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      }}>
        <div>
          <div style={{ fontSize: 12, opacity: 0.7 }}>שלום,</div>
          <div style={{ fontSize: 20, fontWeight: 800 }}>{contractorName || 'קבלן'}</div>
        </div>
        <div style={{ textAlign: 'left' }}>
          <div style={{ fontSize: 28, fontWeight: 800 }}>{openTasks.length}</div>
          <div style={{ fontSize: 12, opacity: 0.8 }}>משימות פתוחות</div>
        </div>
      </div>

      {/* Task status bar */}
      <BarChart title="משימות לפי סטטוס" data={taskBarData} height={120} />

      {/* Open tasks list */}
      {openTasks.length > 0 && (
        <div style={{ background: 'var(--ybp-panel,#fff)', borderRadius: 12, padding: 16, border: '1px solid var(--ybp-border,#e5e7eb)' }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--ybp-ink,#111827)', marginBottom: 10 }}>
            🔴 משימות לטיפול
          </div>
          {openTasks.slice(0,5).map((t, i) => (
            <div key={i} style={{
              padding: '10px 0', borderBottom: i < openTasks.length - 1 ? '1px solid var(--ybp-border,#e5e7eb)' : 'none',
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            }}>
              <div>
                <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ybp-ink,#111827)' }}>{t.title}</div>
                <div style={{ fontSize: 11, color: GRAY }}>יעד: {t.due}</div>
              </div>
              <span style={{
                padding: '2px 8px', borderRadius: 99, fontSize: 11, fontWeight: 600,
                background: t.severity === 'critical' ? '#fef2f2' : '#fffbeb',
                color: t.severity === 'critical' ? RED : AMBER,
              }}>
                {t.severity === 'critical' ? 'דחוף' : 'רגיל'}
              </span>
            </div>
          ))}
          <button onClick={() => onNavigate('contractorBoard')} style={{
            marginTop: 12, width: '100%', padding: '9px', borderRadius: 8,
            background: NAVY, color: '#fff', border: 'none',
            fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'Assistant, sans-serif',
          }}>פתח לוח קבלן ←</button>
        </div>
      )}

      {/* Open tenders */}
      {tenders.length > 0 && (
        <div style={{ background: 'var(--ybp-panel,#fff)', borderRadius: 12, padding: 16, border: '1px solid var(--ybp-border,#e5e7eb)' }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--ybp-ink,#111827)', marginBottom: 10 }}>
            📬 מכרזים פתוחים
          </div>
          {tenders.slice(0,3).map((t, i) => (
            <div key={i} style={{
              padding: '10px 0', borderBottom: i < tenders.length - 1 ? '1px solid var(--ybp-border,#e5e7eb)' : 'none',
              display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            }}>
              <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ybp-ink,#111827)' }}>{t.name}</div>
              <div style={{ fontSize: 11, color: GRAY }}>עד {t.submissionDeadline}</div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

// ── DashboardScreen (router) ──────────────────────────────────────────────────
const DashboardScreen = ({ onBack, onOpenProject, onOpenReports, onOpenBudget, onOpenTasks, onOpenMeetings, onOpenTenders, onOpenProtocols, onNewProject, onOpenList, onOpenMeetingsAll, onOpenProjectsNoReport, projectId, session }) => {
  const userSession = session || (window.YBP_AUTH ? window.YBP_AUTH.getSession() : null);
  const role = userSession?.role || 'admin';

  // role-based default tab — dashboard נפתח תמיד כ-PM (Admin/PM)
  // contractor/client מגיעים דרך לינק ייעודי, לא דרך התפריט
  const defaultTab = (role === 'client') ? 'client' : (role === 'contractor') ? 'contractor' : 'pm';
  const effectiveTab = (role === 'contractor' || role === 'client') ? defaultTab : 'pm';
  const [tab, setTab] = useState('pm');

  const navMap = {
    list: onOpenList,
    reports: onOpenReports,
    budget: onOpenBudget,
    tasks: onOpenTasks,
    meetings: onOpenMeetingsAll,
    projectsNoReport: onOpenProjectsNoReport,
    tenders: onOpenTenders,
    protocols: onOpenProtocols,
  };

  const handleNavigate = (screen) => {
    const fn = navMap[screen];
    if (fn) fn();
  };

  const tabs = [
    { k: 'pm', label: 'מנהל פרויקט', icon: '👔' },
    { k: 'client', label: 'לקוח', icon: '🏢' },
    { k: 'contractor', label: 'קבלן', icon: '🦺' },
  ];

  return (
    <div style={{ minHeight: '100vh', background: 'var(--ybp-bg,#f6f7f9)', fontFamily: 'Assistant, sans-serif', direction: 'rtl' }}>
      {/* Header */}
      <div style={{
        background: '#1a2c4a', color: '#fff',
        padding: '14px 20px', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        position: 'sticky', top: 0, zIndex: 50,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
          {onBack && (
            <button onClick={onBack} style={{ background: 'rgba(255,255,255,0.12)', border: '1px solid rgba(255,255,255,0.2)', color: '#fff', cursor: 'pointer', padding: '5px 10px', borderRadius: 6, fontFamily: 'inherit', fontSize: 13 }}>
              ← חזרה
            </button>
          )}
          <div>
            <h1 style={{ margin: 0, fontSize: 18, fontWeight: 700, color: '#fff' }}>לוח בקרה</h1>
            <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.6)' }}>
              {new Date().toLocaleDateString('he-IL', { weekday:'long', day:'numeric', month:'long' })}
            </div>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          {onNewProject && (
            <button onClick={onNewProject} style={{
              padding: '8px 14px', borderRadius: 8,
              background: 'rgba(255,255,255,0.15)', color: '#fff',
              border: '1px solid rgba(255,255,255,0.25)', fontSize: 13, fontWeight: 700,
              cursor: 'pointer', fontFamily: 'Assistant, sans-serif',
              display: 'flex', alignItems: 'center', gap: 6,
            }}>
              <span style={{ fontSize: 16 }}>＋</span> פרויקט חדש
            </button>
          )}
          <button onClick={() => window.toastInfo && window.toastInfo('נתונים מעודכנים')} style={{
            padding: '7px 12px', borderRadius: 8,
            background: 'rgba(255,255,255,0.12)',
            border: '1px solid rgba(255,255,255,0.2)',
            fontSize: 13, cursor: 'pointer', color: '#fff',
          }}>🔄</button>
        </div>
      </div>

      {/* Role tabs */}
      <div style={{
        background: 'var(--ybp-panel,#fff)',
        borderBottom: '1px solid var(--ybp-border,#e5e7eb)',
        display: 'flex', padding: '0 20px',
      }}>
        {tabs.map(t => (
          <button key={t.k} onClick={() => setTab(t.k)} style={{
            padding: '10px 14px', background: 'none', border: 'none', cursor: 'pointer',
            fontSize: 13, fontWeight: tab === t.k ? 700 : 500,
            color: tab === t.k ? NAVY : 'var(--ybp-ink-faint,#6b7280)',
            borderBottom: tab === t.k ? `2.5px solid ${NAVY}` : '2.5px solid transparent',
            fontFamily: 'Assistant, sans-serif',
            display: 'flex', alignItems: 'center', gap: 5,
          }}>
            <span>{t.icon}</span> {t.label}
          </button>
        ))}
      </div>

      {/* Content */}
      <div style={{ maxWidth: 720, margin: '0 auto' }}>
        {tab === 'pm' && <PMDashboard onNavigate={handleNavigate} />}
        {tab === 'client' && <ClientDashboard projectId={projectId} onNavigate={handleNavigate} />}
        {tab === 'contractor' && <ContractorDashboard
          contractorName={userSession?.name}
          onNavigate={handleNavigate}
        />}
      </div>
    </div>
  );
};

Object.assign(window, { DashboardScreen, PMDashboard, ClientDashboard, ContractorDashboard });
})();
