// Global views reached from the Dashboard — all meetings + projects without report
(function(){
const { useState, useEffect } = React;

const NAVY = '#1a2c4a', GRAY = '#6b7280', BLUE = '#2563eb';

const startOfWeek = () => {
  const n = new Date(); n.setHours(0,0,0,0);
  n.setDate(n.getDate() - n.getDay()); // ראשון
  return n;
};
const endOfWeek = () => { const e = new Date(startOfWeek()); e.setDate(e.getDate() + 7); return e; };

const projName = (id) => {
  if (!id) return 'ללא פרויקט';
  try { if (window.resolveProjectName) { const n = window.resolveProjectName(id); if (n) return n; } } catch(_) {}
  const p = ((window.YBP_DATA && YBP_DATA.projects) || []).find(x => x.id === id);
  return p ? p.name : 'ללא פרויקט';
};

// ════════ MeetingsAllScreen — כל הפגישות מכל הפרויקטים ════════
const MeetingsAllScreen = ({ onBack, onOpenProject }) => {
  const [store, setStore] = useState(() => (window.SyncStore ? SyncStore.get() : { meetings: [] }));
  useEffect(() => { if (window.SyncStore) return SyncStore.subscribe(setStore); }, []);

  const meetings = (store.meetings || []).slice()
    .sort((a,b) => String(a.date||'').localeCompare(String(b.date||'')));
  const sw = startOfWeek(), ew = endOfWeek();
  const isThisWeek = (m) => { if (!m.date) return false; const d = new Date(m.date); return d >= sw && d < ew; };
  const thisWeekCount = meetings.filter(isThisWeek).length;

  return (
    <div style={{ minHeight:'100%', background:'var(--ybp-bg,#f6f7f9)', fontFamily:'Assistant,sans-serif', direction:'rtl' }}>
      <div style={{ background:'#fff', borderBottom:'1px solid var(--ybp-border,#e5e7eb)', padding:'14px 24px', display:'flex', alignItems:'center', gap:12 }}>
        <button onClick={onBack} style={{ background:'transparent', border:'none', cursor:'pointer', color:GRAY, fontSize:14, fontFamily:'inherit' }}>← חזרה</button>
        <div style={{ width:1, height:24, background:'var(--ybp-border,#e5e7eb)' }}/>
        <div>
          <div style={{ fontSize:11, color:GRAY, fontWeight:600 }}>כל הפרויקטים</div>
          <div style={{ fontSize:17, fontWeight:700, color:'#1f2937' }}>פגישות — {thisWeekCount} השבוע · {meetings.length} סה״כ</div>
        </div>
      </div>
      <div style={{ maxWidth:760, margin:'0 auto', padding:'20px 24px' }}>
        {meetings.length === 0 ? (
          <div style={{ background:'#fff', border:'1px solid var(--ybp-border,#e5e7eb)', borderRadius:12, padding:48, textAlign:'center' }}>
            <div style={{ fontSize:32, marginBottom:8 }}>📅</div>
            <div style={{ fontSize:14, color:GRAY }}>אין פגישות מתוזמנות</div>
          </div>
        ) : meetings.map(m => (
          <div key={m.id} onClick={() => onOpenProject && onOpenProject(m.projectId)}
            style={{ background:'#fff', border:'1px solid var(--ybp-border,#e5e7eb)', borderRadius:10, padding:14, marginBottom:10, cursor:'pointer', display:'flex', gap:12, alignItems:'center' }}
            onMouseEnter={e => e.currentTarget.style.boxShadow='0 4px 12px rgba(0,0,0,0.08)'}
            onMouseLeave={e => e.currentTarget.style.boxShadow='none'}>
            <div style={{ textAlign:'center', flexShrink:0, minWidth:54 }}>
              <div style={{ fontSize:18, fontWeight:800, color:NAVY }}>{m.date ? m.date.slice(8,10) : '—'}</div>
              <div style={{ fontSize:10, color:GRAY }}>{m.date ? m.date.slice(5,7)+'/'+m.date.slice(0,4) : ''}</div>
            </div>
            <div style={{ width:1, alignSelf:'stretch', background:'var(--ybp-border,#e5e7eb)' }}/>
            <div style={{ flex:1, minWidth:0 }}>
              <div style={{ display:'flex', alignItems:'center', gap:8 }}>
                <span style={{ fontSize:13.5, fontWeight:700, color:'#1f2937' }}>{m.title || 'פגישה'}</span>
                {isThisWeek(m) && <span style={{ fontSize:10, fontWeight:700, background:'#eff6ff', color:BLUE, padding:'1px 7px', borderRadius:99 }}>השבוע</span>}
              </div>
              <div style={{ fontSize:11.5, color:GRAY, marginTop:2 }}>
                📁 {projName(m.projectId)}{m.time ? ' · ' + m.time : ''}{m.location ? ' · 📍 ' + m.location : ''}
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

// ════════ ProjectsNoReportScreen — פרויקטים פעילים ללא דיווח ב-7 ימים ════════
const ProjectsNoReportScreen = ({ onBack, onOpenProject, onCreateWeekly }) => {
  const [store, setStore] = useState(() => (window.SyncStore ? SyncStore.get() : { reports: [] }));
  useEffect(() => { if (window.SyncStore) return SyncStore.subscribe(setStore); }, []);

  const projects = (window.YBP_DATA && YBP_DATA.projects) || [];
  const active = projects.filter(p => p.status !== 'הושלם' && p.status !== 'בוטל');
  const reports = store.reports || [];
  const weekAgo = Date.now() - 7*86400000;
  const recent = reports.filter(r => new Date(r.date || r.createdAt).getTime() > weekAgo);
  const noReport = active.filter(p => !recent.find(r => r.projectId === p.id));

  const lastReport = (pid) => {
    const rs = reports.filter(r => r.projectId === pid)
      .sort((a,b) => new Date(b.date||b.createdAt) - new Date(a.date||a.createdAt));
    return rs[0] ? String(rs[0].date || rs[0].createdAt || '').slice(0,10) : null;
  };

  return (
    <div style={{ minHeight:'100%', background:'var(--ybp-bg,#f6f7f9)', fontFamily:'Assistant,sans-serif', direction:'rtl' }}>
      <div style={{ background:'#fff', borderBottom:'1px solid var(--ybp-border,#e5e7eb)', padding:'14px 24px', display:'flex', alignItems:'center', gap:12 }}>
        <button onClick={onBack} style={{ background:'transparent', border:'none', cursor:'pointer', color:GRAY, fontSize:14, fontFamily:'inherit' }}>← חזרה</button>
        <div style={{ width:1, height:24, background:'var(--ybp-border,#e5e7eb)' }}/>
        <div>
          <div style={{ fontSize:11, color:GRAY, fontWeight:600 }}>דורש טיפול</div>
          <div style={{ fontSize:17, fontWeight:700, color:'#1f2937' }}>פרויקטים ללא דיווח השבוע ({noReport.length})</div>
        </div>
      </div>
      <div style={{ maxWidth:760, margin:'0 auto', padding:'20px 24px' }}>
        {noReport.length === 0 ? (
          <div style={{ background:'#fff', border:'1px solid var(--ybp-border,#e5e7eb)', borderRadius:12, padding:48, textAlign:'center' }}>
            <div style={{ fontSize:32, marginBottom:8 }}>🎉</div>
            <div style={{ fontSize:14, color:GRAY }}>כל הפרויקטים הפעילים דיווחו השבוע</div>
          </div>
        ) : noReport.map(p => {
          const last = lastReport(p.id);
          return (
            <div key={p.id} style={{ background:'#fff', border:'1px solid var(--ybp-border,#e5e7eb)', borderRadius:10, padding:14, marginBottom:10, display:'flex', gap:12, alignItems:'center' }}>
              <div style={{ flex:1, minWidth:0, cursor:'pointer' }} onClick={() => onOpenProject && onOpenProject(p.id)}>
                <div style={{ fontSize:13.5, fontWeight:700, color:'#1f2937' }}>{p.name}</div>
                <div style={{ fontSize:11.5, color:GRAY, marginTop:2 }}>
                  {p.client || ''}{last ? ' · דיווח אחרון: ' + last : ' · אין דיווחים'}
                </div>
              </div>
              <button onClick={() => onCreateWeekly && onCreateWeekly(p.id)} style={{
                flexShrink:0, background:NAVY, color:'#fff', border:'none',
                padding:'8px 14px', borderRadius:8, fontSize:12.5, fontWeight:600,
                cursor:'pointer', fontFamily:'inherit',
              }}>+ דוח שבועי</button>
            </div>
          );
        })}
      </div>
    </div>
  );
};

Object.assign(window, { MeetingsAllScreen, ProjectsNoReportScreen });
})();
