// Schedule Meeting Screen — Google Calendar embed + meetings list + new meeting form
(function(){
const { useState, useEffect, useRef } = React;

// ─────────────────────────────────────────────────────
// SCHEDULE MEETING FORM — modal
// ─────────────────────────────────────────────────────
const ScheduleMeetingModal = ({ projectId, onClose, onSaved }) => {
  const project = YBP_DATA.projects.find(p => p.id === projectId);
  const contacts = (YBP_DATA.projectDetail?.contacts || []);

  const tomorrow = (() => { const d = new Date(); d.setDate(d.getDate()+1); return d.toISOString().slice(0,10); })();

  const [title, setTitle]       = useState('');
  const [date, setDate]         = useState(tomorrow);
  const [time, setTime]         = useState('10:00');
  const [duration, setDuration] = useState(60);
  const [location, setLocation] = useState('האתר');
  const [customLoc, setCustomLoc] = useState('');
  const [agenda, setAgenda]     = useState('');
  const [participants, setParticipants] = useState([]);
  const [sendWA, setSendWA]     = useState(true);
  const [sendGmail, setSendGmail] = useState(true);
  const [saved, setSaved]       = useState(false);

  const LOCATIONS = [
    { k: 'האתר',    icon: '🏗️' },
    { k: 'משרד YBP', icon: '🏢' },
    { k: 'זום',     icon: '💻' },
    { k: 'אחר',     icon: '📍' },
  ];

  const toggleParticipant = (name) =>
    setParticipants(prev => prev.includes(name) ? prev.filter(n=>n!==name) : [...prev, name]);

  const gcalLink = () => {
    const start = `${date.replace(/-/g,'')}T${time.replace(':','')}00`;
    const endDate = new Date(`${date}T${time}`);
    endDate.setMinutes(endDate.getMinutes() + duration);
    const end = endDate.toISOString().replace(/[-:]/g,'').slice(0,15);
    const loc = location === 'אחר' ? customLoc : location;
    const details = [agenda, `פרויקט: ${project?.name}`, `משתתפים: ${participants.join(', ')}`].filter(Boolean).join('\n');
    return `https://calendar.google.com/calendar/render?action=TEMPLATE&text=${encodeURIComponent(title)}&dates=${start}/${end}&location=${encodeURIComponent(loc)}&details=${encodeURIComponent(details)}`;
  };

  const waText = () => {
    const loc = location === 'אחר' ? customLoc : location;
    return `*📅 פגישה: ${title}*\n\n🗓️ ${date} בשעה ${time} (${duration} דק׳)\n📍 ${loc}\n${agenda ? '📝 ' + agenda + '\n' : ''}👥 ${participants.join(', ') || '—'}\n\n*${project?.name}*`;
  };

  const gmailSubject = () => `פגישה: ${title} — ${date} ${time}`;
  const gmailBody = () => {
    const loc = location === 'אחר' ? customLoc : location;
    return `שלום,\n\nמוזמנים לפגישה:\n\nנושא: ${title}\nתאריך: ${date}\nשעה: ${time} (${duration} דק׳)\nמיקום: ${loc}\n${agenda ? 'אג\'נדה: ' + agenda + '\n' : ''}\nמשתתפים: ${participants.join(', ') || '—'}\n\nYBPROJECTS · ${project?.name}`;
  };

  const handleSave = () => {
    if (!title.trim()) return;
    // save to SyncStore
    const meeting = {
      id: `MTG-${Date.now()}`,
      projectId,
      title: title.trim(),
      date, time, duration,
      location: location === 'אחר' ? customLoc : location,
      agenda,
      participants,
      status: 'upcoming',
      attendees: participants.length,
      createdAt: new Date().toISOString(),
    };
    const store = SyncStore.get();
    SyncStore._set({ ...store, meetings: [...(store.meetings||[]), meeting] });
    setSaved(true);
    onSaved?.(meeting);

    // open gcal
    window.open(gcalLink(), '_blank');

    // send WA
    if (sendWA) {
      setTimeout(() => window.open(`https://wa.me/?text=${encodeURIComponent(waText())}`, '_blank'), 300);
    }
    // send Gmail
    if (sendGmail) {
      const participantEmails = contacts.filter(c => participants.includes(c.name)).map(c=>c.email).filter(Boolean);
      const url = typeof buildGmailUrl !== 'undefined'
        ? buildGmailUrl({ to: participantEmails, subject: gmailSubject(), body: gmailBody() })
        : `https://mail.google.com/mail/?view=cm&su=${encodeURIComponent(gmailSubject())}&body=${encodeURIComponent(gmailBody())}`;
      setTimeout(() => window.open(url, '_blank'), 600);
    }

    setTimeout(() => { onClose(); }, 1000);
  };

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

  return (
    <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.55)', zIndex:9999, display:'flex', alignItems:'flex-end', justifyContent:'center', padding:0 }}
      onClick={e => e.target===e.currentTarget && onClose()}>
      <div style={{
        background:'#fff', borderRadius:'16px 16px 0 0', width:'100%', maxWidth:540,
        maxHeight:'92vh', overflowY:'auto', fontFamily:'Assistant,sans-serif', direction:'rtl',
        boxShadow:'0 -8px 40px rgba(0,0,0,0.2)',
      }}>
        {/* Header */}
        <div style={{ padding:'16px 20px 12px', borderBottom:'1px solid #e5e7eb', display:'flex', alignItems:'center', gap:10, position:'sticky', top:0, background:'#fff', zIndex:1 }}>
          <div style={{ width:4, height:28, background:'#1a2c4a', borderRadius:2 }}/>
          <div>
            <div style={{ fontSize:16, fontWeight:700, color:'#1f2937' }}>תאם פגישה חדשה</div>
            <div style={{ fontSize:11, color:'#6b7280' }}>{project?.name}</div>
          </div>
          <button onClick={onClose} style={{ marginRight:'auto', background:'none', border:'none', fontSize:22, cursor:'pointer', color:'#9ca3af', lineHeight:1 }}>✕</button>
        </div>

        {saved ? (
          <div style={{ padding:40, textAlign:'center' }}>
            <div style={{ fontSize:48, marginBottom:12 }}>✅</div>
            <div style={{ fontSize:16, fontWeight:700, color:'#065f46' }}>הפגישה נשמרה!</div>
            <div style={{ fontSize:13, color:'#6b7280', marginTop:6 }}>נפתח Google Calendar + הזמנות נשלחות</div>
          </div>
        ) : (
          <div style={{ padding:'18px 20px', display:'flex', flexDirection:'column', gap:16 }}>

            {/* Title */}
            <div>
              <label style={{ fontSize:12, fontWeight:700, color:'#374151', display:'block', marginBottom:5 }}>נושא הפגישה *</label>
              <input value={title} onChange={e=>setTitle(e.target.value)} placeholder="לדוג׳: ישיבת תיאום שבועית" style={{ ...inp, fontSize:15, fontWeight:600 }} autoFocus/>
            </div>

            {/* Date + Time */}
            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
              <div>
                <label style={{ fontSize:12, fontWeight:700, color:'#374151', display:'block', marginBottom:5 }}>תאריך</label>
                <input type="date" value={date} onChange={e=>setDate(e.target.value)} style={inp}/>
              </div>
              <div>
                <label style={{ fontSize:12, fontWeight:700, color:'#374151', display:'block', marginBottom:5 }}>שעה</label>
                <input type="time" value={time} onChange={e=>setTime(e.target.value)} style={inp}/>
              </div>
            </div>

            {/* Duration */}
            <div>
              <label style={{ fontSize:12, fontWeight:700, color:'#374151', display:'block', marginBottom:7 }}>משך הפגישה</label>
              <div style={{ display:'flex', gap:8 }}>
                {[30,60,90,120].map(d => (
                  <button key={d} onClick={()=>setDuration(d)} style={{
                    flex:1, padding:'8px 0', borderRadius:6, fontSize:12, fontWeight:700, cursor:'pointer', fontFamily:'inherit',
                    border: duration===d ? '2px solid #1a2c4a' : '1px solid #e5e7eb',
                    background: duration===d ? '#1a2c4a' : '#fff',
                    color: duration===d ? '#fff' : '#6b7280',
                  }}>{d === 120 ? '2ש׳' : `${d}ד׳`}</button>
                ))}
              </div>
            </div>

            {/* Location */}
            <div>
              <label style={{ fontSize:12, fontWeight:700, color:'#374151', display:'block', marginBottom:7 }}>מיקום</label>
              <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
                {LOCATIONS.map(l => (
                  <button key={l.k} onClick={()=>setLocation(l.k)} style={{
                    padding:'8px 14px', borderRadius:6, fontSize:12, fontWeight:600, cursor:'pointer', fontFamily:'inherit',
                    border: location===l.k ? '2px solid #1a2c4a' : '1px solid #e5e7eb',
                    background: location===l.k ? '#e8f0fe' : '#fff',
                    color: location===l.k ? '#1a2c4a' : '#6b7280',
                    display:'flex', alignItems:'center', gap:5,
                  }}><span>{l.icon}</span>{l.k}</button>
                ))}
              </div>
              {location === 'אחר' && (
                <input value={customLoc} onChange={e=>setCustomLoc(e.target.value)} placeholder="הזן כתובת / שם מקום..." style={{ ...inp, marginTop:8 }}/>
              )}
            </div>

            {/* Participants */}
            {contacts.length > 0 && (
              <div>
                <label style={{ fontSize:12, fontWeight:700, color:'#374151', display:'block', marginBottom:7 }}>משתתפים</label>
                <div style={{ display:'flex', flexWrap:'wrap', gap:8 }}>
                  {contacts.map(c => {
                    const sel = participants.includes(c.name);
                    return (
                      <button key={c.id} onClick={()=>toggleParticipant(c.name)} style={{
                        padding:'6px 12px', borderRadius:20, fontSize:12, fontWeight:600, cursor:'pointer', fontFamily:'inherit',
                        border: sel ? '2px solid #1a2c4a' : '1px solid #e5e7eb',
                        background: sel ? '#1a2c4a' : '#fff',
                        color: sel ? '#fff' : '#374151',
                        display:'flex', alignItems:'center', gap:6,
                      }}>
                        <Avatar name={c.name} size={18}/>
                        {c.name}
                      </button>
                    );
                  })}
                </div>
              </div>
            )}

            {/* Agenda */}
            <div>
              <label style={{ fontSize:12, fontWeight:700, color:'#374151', display:'block', marginBottom:5 }}>אג׳נדה <span style={{ fontWeight:400, color:'#9ca3af' }}>(אופציונלי)</span></label>
              <textarea value={agenda} onChange={e=>setAgenda(e.target.value)} rows={2} placeholder="נושאים לדיון..." style={{ ...inp, resize:'vertical', lineHeight:1.5 }}/>
            </div>

            {/* Send options */}
            <div style={{ background:'#f9fafb', borderRadius:8, padding:'12px 14px' }}>
              <div style={{ fontSize:12, fontWeight:700, color:'#374151', marginBottom:9 }}>שליחת הזמנות</div>
              <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
                {[
                  { id:'wa', label:'WhatsApp', color:'#25d366', icon:<svg width="14" height="14" viewBox="0 0 24 24" fill="#fff"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347z"/><path d="M12 2C6.477 2 2 6.477 2 12c0 1.89.525 3.66 1.438 5.168L2 22l4.832-1.438A9.96 9.96 0 0012 22c5.523 0 10-4.477 10-10S17.523 2 12 2z"/></svg>, val:sendWA, set:setSendWA },
                  { id:'gmail', label:'Gmail', color:'#ea4335', icon:<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>, val:sendGmail, set:setSendGmail },
                ].map(opt => (
                  <label key={opt.id} style={{ display:'flex', alignItems:'center', gap:10, cursor:'pointer' }}>
                    <div onClick={()=>opt.set(v=>!v)} style={{
                      width:36, height:20, borderRadius:10, background: opt.val ? opt.color : '#e5e7eb',
                      position:'relative', transition:'background .2s', cursor:'pointer', flexShrink:0,
                    }}>
                      <div style={{ position:'absolute', top:2, right: opt.val ? 18 : 2, width:16, height:16, borderRadius:8, background:'#fff', transition:'right .2s', boxShadow:'0 1px 3px rgba(0,0,0,0.2)' }}/>
                    </div>
                    <span style={{ width:24, height:24, background:opt.val ? opt.color : '#e5e7eb', borderRadius:5, display:'flex', alignItems:'center', justifyContent:'center', transition:'background .2s' }}>{opt.icon}</span>
                    <span style={{ fontSize:13, color:'#374151', fontWeight:600 }}>{opt.label}</span>
                  </label>
                ))}
              </div>
            </div>

            {/* Google Calendar note */}
            <div style={{ display:'flex', alignItems:'center', gap:8, padding:'10px 12px', background:'#e8f0fe', borderRadius:8, fontSize:12, color:'#1a56db' }}>
              <svg width="16" height="16" viewBox="0 0 48 48" style={{ flexShrink:0 }}>
                <rect x="6" y="8" width="36" height="34" rx="3" fill="#fff" stroke="#dadce0"/>
                <rect x="6" y="8" width="36" height="8" fill="#4285F4"/>
                <text x="24" y="32" fontSize="14" fill="#3c4043" textAnchor="middle" fontWeight="700" fontFamily="Roboto">G</text>
              </svg>
              <span>אירוע ייפתח ב-Google Calendar לאישור ושמירה</span>
            </div>

            {/* Submit */}
            <button onClick={handleSave} disabled={!title.trim()} style={{
              width:'100%', padding:'14px', borderRadius:8, border:'none', fontFamily:'inherit',
              background: title.trim() ? '#1a2c4a' : '#e5e7eb',
              color: title.trim() ? '#fff' : '#9ca3af',
              fontWeight:700, fontSize:15, cursor: title.trim() ? 'pointer' : 'not-allowed',
              display:'flex', alignItems:'center', justifyContent:'center', gap:8,
            }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
              תאם פגישה + שלח הזמנות
            </button>
          </div>
        )}
      </div>
    </div>
  );
};

// ─────────────────────────────────────────────────────
// CALENDAR IFRAME PANEL
// ─────────────────────────────────────────────────────
const CalendarIframePanel = ({ projectId }) => {
  const storageKey = `ybp_gcal_url_${projectId}`;
  const [embedUrl, setEmbedUrl] = useState(() => {
    try { return localStorage.getItem(storageKey) || ''; } catch { return ''; }
  });
  const [editing, setEditing] = useState(false);
  const [draft, setDraft] = useState(embedUrl);

  // מייל ה-session — מה שמחובר עכשיו
  const sessionEmail = (() => {
    try {
      const s = JSON.parse(localStorage.getItem('ybp_auth_session') || '{}');
      return s.email || window.YBP_USER?.email || '';
    } catch { return window.YBP_USER?.email || ''; }
  })();

  // בנה URL אוטומטי מהמייל של ה-session
  const buildMyCalendarUrl = (email) => {
    if (!email) return '';
    const encoded = encodeURIComponent(email);
    return `https://calendar.google.com/calendar/embed?src=${encoded}&ctz=Asia%2FJerusalem&authuser=${encoded}`;
  };

  const useMyCalendar = () => {
    const url = buildMyCalendarUrl(sessionEmail);
    if (!url) {
      window.toastError ? window.toastError('לא נמצא מייל ב-session') : alert('לא נמצא מייל ב-session');
      return;
    }
    setDraft(url);
    setEmbedUrl(url);
    try { localStorage.setItem(storageKey, url); } catch {}
    setEditing(false);
    window.toastSuccess && window.toastSuccess('יומן חובר ✓');
  };

  const saveUrl = () => {
    let url = draft.trim();
    const email = window.YBP_USER?.email || '';
    if (email && url && !url.includes('authuser=')) {
      url += (url.includes('?') ? '&' : '?') + `authuser=${encodeURIComponent(email)}`;
    }
    setEmbedUrl(url);
    try { localStorage.setItem(storageKey, url); } catch {}
    setEditing(false);
  };

  if (!embedUrl || editing) {
    return (
      <div style={{ flex:1, display:'flex', flexDirection:'column', alignItems:'center', justifyContent:'center', padding:32, gap:20, background:'#f9fafb', borderRadius:10, border:'2px dashed #e5e7eb', minHeight:380 }}>
        <div style={{ textAlign:'center' }}>
          <div style={{ fontSize:40, marginBottom:12 }}>📅</div>
          <div style={{ fontSize:16, fontWeight:700, color:'#1f2937', marginBottom:6 }}>
            {editing ? 'עדכן את ה-Embed URL שלך' : 'חבר את Google Calendar שלך'}
          </div>
          {sessionEmail && !editing && (
            <div style={{ fontSize:13, color:'#6b7280', maxWidth:360, lineHeight:1.5 }}>
              היומן הראשי של <b style={{ direction:'ltr', display:'inline-block' }}>{sessionEmail}</b> יחובר אוטומטית
            </div>
          )}
        </div>

        {sessionEmail && !editing && (
          <button onClick={useMyCalendar} style={{
            padding:'12px 28px', borderRadius:8, border:'none', fontFamily:'inherit',
            background:'#1d4ed8', color:'#fff',
            fontWeight:700, fontSize:15, cursor:'pointer',
            display:'flex', alignItems:'center', gap:8,
            boxShadow:'0 2px 8px rgba(29, 78, 216, 0.25)',
          }}>
            <svg width="18" height="18" viewBox="0 0 48 48">
              <rect x="6" y="8" width="36" height="34" rx="3" fill="#fff" stroke="#dadce0"/>
              <rect x="6" y="8" width="36" height="8" fill="#4285F4"/>
              <text x="24" y="30" fontSize="12" fill="#3c4043" textAnchor="middle" fontWeight="700">G</text>
            </svg>
            השתמש ביומן שלי
          </button>
        )}

        {/* ─── מתקדם: הדבק URL ידני ─── */}
        <details style={{ width:'100%', maxWidth:440 }}>
          <summary style={{ cursor:'pointer', fontSize:12, color:'#6b7280', textAlign:'center', padding:6 }}>
            ⚙️ אפשרות מתקדמת — הדבק URL ידני (ליומן אחר / משותף)
          </summary>
          <div style={{ marginTop:12, display:'flex', flexDirection:'column', gap:12 }}>
            <div style={{ fontSize:12, color:'#6b7280', lineHeight:1.6, padding:'10px 14px', background:'#fffbeb', borderRadius:7, border:'1px solid #fde68a' }}>
              <div style={{ marginBottom: 6 }}>
                <b>🇮🇱 בעברית:</b> Google Calendar → ⚙️ הגדרות → גלול ל-<b>"הגדרות עבור היומנים שלי"</b> → לחץ על שם היומן → <b>שילוב יומן</b> → העתק את כתובת ה-iframe
              </div>
              <div style={{ direction:'ltr', textAlign:'left' }}>
                <b>🇺🇸 English:</b> Google Calendar → ⚙️ Settings → scroll to <b>"Settings for my calendars"</b> → click your calendar name → <b>Integrate calendar</b> → copy the "Public URL" or "Embed code"
              </div>
            </div>
            <input
              value={draft}
              onChange={e=>setDraft(e.target.value)}
              placeholder="https://calendar.google.com/calendar/embed?src=..."
              style={{ width:'100%', padding:'10px 14px', border:'1px solid #e5e7eb', borderRadius:8, fontSize:13, fontFamily:'inherit', boxSizing:'border-box', direction:'ltr' }}
            />
            <div style={{ display:'flex', gap:10, justifyContent:'center' }}>
              <button onClick={saveUrl} disabled={!draft.trim()} style={{
                padding:'10px 24px', borderRadius:7, border:'none', fontFamily:'inherit',
                background: draft.trim() ? '#1a2c4a' : '#e5e7eb',
                color: draft.trim() ? '#fff' : '#9ca3af',
                fontWeight:700, fontSize:14, cursor: draft.trim() ? 'pointer' : 'not-allowed',
              }}>שמור URL מותאם</button>
              {editing && (
                <button onClick={()=>setEditing(false)} style={{ padding:'10px 16px', borderRadius:7, border:'1px solid #e5e7eb', background:'#fff', color:'#6b7280', fontSize:13, cursor:'pointer', fontFamily:'inherit' }}>ביטול</button>
              )}
            </div>
          </div>
        </details>

        <div style={{ fontSize:11, color:'#9ca3af', textAlign:'center', maxWidth:360 }}>
          הכתובת נשמרת בדפדפן שלך בלבד ולא נשלחת לשום מקום
        </div>
      </div>
    );
  }

  return (
    <div style={{ flex:1, display:'flex', flexDirection:'column', gap:8 }}>
      <div style={{ display:'flex', alignItems:'center', gap:8, padding:'6px 10px', background:'#e8f0fe', borderRadius:8, fontSize:12, color:'#1a56db' }}>
        <svg width="14" height="14" viewBox="0 0 48 48" style={{ flexShrink:0 }}>
          <rect x="6" y="8" width="36" height="34" rx="3" fill="#fff" stroke="#dadce0"/>
          <rect x="6" y="8" width="36" height="8" fill="#4285F4"/>
          <text x="24" y="30" fontSize="12" fill="#3c4043" textAnchor="middle" fontWeight="700">G</text>
        </svg>
        <span style={{ flex:1 }}>Google Calendar מחובר</span>
        <button onClick={()=>{ setDraft(embedUrl); setEditing(true); }} style={{ background:'none', border:'none', fontSize:11, color:'#1a56db', cursor:'pointer', fontFamily:'inherit', textDecoration:'underline' }}>שנה</button>
      </div>
      <iframe
        src={embedUrl}
        style={{ flex:1, border:'1px solid #e5e7eb', borderRadius:10, minHeight:520, width:'100%' }}
        frameBorder="0"
        scrolling="no"
        title="Google Calendar"
      />
    </div>
  );
};

// ─────────────────────────────────────────────────────
// MEETINGS LIST PANEL
// ─────────────────────────────────────────────────────
const MeetingsListPanel = ({ projectId, onOpenReport, onNewMeeting, onOpenMeetingRecorder }) => {
  const [store, setStore] = useState(SyncStore.get());
  useEffect(() => SyncStore.subscribe(setStore), []);

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

  const upcoming = allMeetings.filter(m => m.status !== 'past');
  const past = allMeetings.filter(m => m.status === 'past');

  return (
    <div style={{ display:'flex', flexDirection:'column', gap:16 }}>

      {/* Action buttons */}
      <div style={{ display:'flex', gap:10 }}>
        <button onClick={onNewMeeting} style={{
          flex:1, padding:'12px', borderRadius:8, border:'none', fontFamily:'inherit',
          background:'#1a2c4a', color:'#fff', fontWeight:700, fontSize:14,
          cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', gap:8,
        }}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
          תאם פגישה חדשה
        </button>
        {onOpenMeetingRecorder && (
          <button onClick={onOpenMeetingRecorder} style={{
            padding:'12px 16px', borderRadius:8, border:'none', fontFamily:'inherit',
            background:'#dc2626', color:'#fff', fontWeight:700, fontSize:13,
            cursor:'pointer', display:'flex', alignItems:'center', gap:7,
          }}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/>
              <path d="M19 10v2a7 7 0 0 1-14 0v-2"/>
              <line x1="12" y1="19" x2="12" y2="23"/>
              <line x1="8" y1="23" x2="16" y2="23"/>
            </svg>
            הקלט
          </button>
        )}
      </div>

      {/* Upcoming */}
      <div style={{ background:'#fff', border:'1px solid var(--v1-border)', borderRadius:10, overflow:'hidden' }}>
        <div style={{ padding:'12px 16px', borderBottom:'1px solid var(--v1-border)', background:'#fafbfc', fontSize:12.5, fontWeight:700, display:'flex', alignItems:'center', gap:8 }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#1a2c4a" strokeWidth="2"><rect x="3" y="4" width="18" height="18" rx="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
          פגישות קרובות
          <span style={{ marginRight:'auto', background:'#e8f0fe', color:'#1a56db', fontSize:11, fontWeight:700, padding:'2px 8px', borderRadius:10 }}>{upcoming.length}</span>
        </div>
        {upcoming.length === 0 ? (
          <div style={{ padding:'24px 16px', textAlign:'center', color:'#9ca3af', fontSize:13 }}>
            אין פגישות מתוכננות<br/>
            <span style={{ fontSize:11 }}>לחץ "תאם פגישה חדשה" למעלה</span>
          </div>
        ) : upcoming.map(m => (
          <div key={m.id} style={{ padding:'12px 16px', borderTop:'1px solid var(--v1-border)', display:'flex', alignItems:'flex-start', gap:12 }}>
            <div style={{
              width:4, height:36, borderRadius:2, flexShrink:0, marginTop:2,
              background: m.status==='today' ? '#dc2626' : '#1a2c4a',
            }}/>
            <div style={{ flex:1, minWidth:0 }}>
              <div style={{ display:'flex', alignItems:'center', gap:6, marginBottom:3, flexWrap:'wrap' }}>
                <span style={{ fontSize:13, fontWeight:600, color:'#1f2937' }}>{m.title}</span>
                {m.status==='today' && <span style={{ fontSize:10, background:'#fee2e2', color:'#991b1b', padding:'2px 6px', borderRadius:3, fontWeight:700 }}>היום</span>}
              </div>
              <div style={{ fontSize:11.5, color:'#6b7280', display:'flex', gap:10, flexWrap:'wrap' }}>
                <span>🗓️ {m.date} · {m.time}</span>
                <span>⏱️ {m.duration||60}ד׳</span>
                <span>📍 {m.location}</span>
                {m.attendees && <span>👥 {m.attendees}</span>}
              </div>
              {m.agenda && <div style={{ fontSize:11.5, color:'#6b7280', marginTop:3, fontStyle:'italic' }}>📝 {m.agenda}</div>}
            </div>
            <button onClick={()=>window.open(`https://calendar.google.com/calendar/r`, '_blank')} style={{
              padding:'5px 10px', borderRadius:5, border:'1px solid #e5e7eb', background:'#fff',
              fontSize:11, color:'#4285F4', cursor:'pointer', fontFamily:'inherit', fontWeight:600, flexShrink:0,
            }}>
              📅 יומן
            </button>
          </div>
        ))}
      </div>

      {/* Past */}
      {past.length > 0 && (
        <div style={{ background:'#fff', border:'1px solid var(--v1-border)', borderRadius:10, overflow:'hidden' }}>
          <div style={{ padding:'12px 16px', borderBottom:'1px solid var(--v1-border)', background:'#fafbfc', fontSize:12.5, fontWeight:700, color:'#6b7280' }}>
            היסטוריית פגישות
          </div>
          {past.map(m => (
            <div key={m.id} style={{ padding:'11px 16px', borderTop:'1px solid var(--v1-border)', display:'flex', alignItems:'center', gap:10 }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#10b981" strokeWidth="2.5"><polyline points="20 6 9 17 4 12"/></svg>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ fontSize:12.5, fontWeight:600, color:'#374151' }}>{m.title}</div>
                <div style={{ fontSize:11, color:'#9ca3af' }}>{m.date} · {m.location}</div>
              </div>
              {m.reportId && (
                <button onClick={()=>onOpenReport?.(m.reportId)} style={{
                  background:'#1a2c4a', color:'#fff', border:'none',
                  padding:'4px 10px', borderRadius:4, fontSize:10.5,
                  cursor:'pointer', fontFamily:'ui-monospace, monospace', fontWeight:700,
                }}>{m.reportId}</button>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

// ─────────────────────────────────────────────────────
// MAIN: ProjectMeetingsWithCalendar
// ─────────────────────────────────────────────────────
const ProjectMeetingsWithCalendar = ({ projectId, onBack, onOpenReport, onNewMeeting, onOpenMeetingRecorder }) => {
  const [tab, setTab] = useState('calendar'); // 'calendar' | 'meetings'
  const [showScheduleModal, setShowScheduleModal] = useState(false);

  const project = YBP_DATA.projects.find(p => p.id === projectId);

  const handleNewMeeting = () => setShowScheduleModal(true);

  return (
    <div style={{ minHeight: '100%', background: 'var(--v1-bg,#f6f7f9)', fontFamily: 'Assistant, sans-serif', direction: 'rtl' }}>
      {/* Header */}
      <div style={{
        background: '#1a2c4a', color: '#fff',
        padding: '14px 28px', display: 'flex', alignItems: 'center', gap: 12,
        position: 'sticky', top: 0, zIndex: 50,
      }}>
        <button onClick={onBack} style={{ background: 'rgba(255,255,255,0.12)', border: '1px solid rgba(255,255,255,0.2)', color: '#fff', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 4, fontSize: 13, padding: '5px 10px', borderRadius: 6, fontFamily: 'inherit' }}>
          ← חזרה
        </button>
        <div style={{ width: 1, height: 20, background: 'rgba(255,255,255,0.2)' }}/>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 10, color: 'rgba(255,255,255,0.6)', fontWeight: 600, letterSpacing: 0.3 }}>{project?.name}</div>
          <div style={{ fontSize: 17, fontWeight: 700 }}>פגישות ולו״ז</div>
        </div>
        <button onClick={handleNewMeeting} style={{
          background: 'rgba(255,255,255,0.15)', color: '#fff', border: '1px solid rgba(255,255,255,0.25)',
          padding: '8px 16px', borderRadius: 6, fontSize: 13, fontWeight: 600,
          cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 7, fontFamily: 'inherit',
        }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
          תאם פגישה
        </button>
      </div>

      {showScheduleModal && (
        <ScheduleMeetingModal
          projectId={projectId}
          onClose={() => setShowScheduleModal(false)}
          onSaved={() => {}}
        />
      )}

      {/* Tab bar */}
      <div style={{ padding:'0 28px', borderBottom:'2px solid var(--v1-border,#e5e7eb)', background:'#fff', display:'flex', gap:0 }}>
        {[
          { k:'calendar', label:'📅 יומן Google' },
          { k:'meetings', label:'📋 פגישות' },
        ].map(t => (
          <button key={t.k} onClick={()=>setTab(t.k)} style={{
            padding:'13px 22px', border:'none', background:'none', fontFamily:'inherit',
            fontSize:13.5, fontWeight:700, cursor:'pointer',
            color: tab===t.k ? '#1a2c4a' : '#9ca3af',
            borderBottom: tab===t.k ? '3px solid #1a2c4a' : '3px solid transparent',
            marginBottom:-2, transition:'color .15s',
          }}>{t.label}</button>
        ))}
      </div>

      {/* Content */}
      <div style={{ padding:'20px 28px', maxWidth:1200, margin:'0 auto' }}>
        {tab === 'calendar' && (
          <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
            <div style={{ display:'flex', alignItems:'center', gap:10, padding:'10px 14px', background:'#fffbeb', border:'1px solid #fde68a', borderRadius:8, fontSize:12.5, color:'#b45309' }}>
              <span>💡</span>
              <span>היומן מציג את <b>כל הפגישות שלך</b> ב-Google Calendar — לא רק פגישות הפרויקט הזה</span>
            </div>
            <CalendarIframePanel projectId={projectId}/>
          </div>
        )}
        {tab === 'meetings' && (
          <div style={{ maxWidth:600 }}>
            <MeetingsListPanel
              projectId={projectId}
              onOpenReport={onOpenReport}
              onNewMeeting={handleNewMeeting}
              onOpenMeetingRecorder={onOpenMeetingRecorder}
            />
          </div>
        )}
      </div>
    </div>
  );
};

Object.assign(window, { ProjectMeetingsWithCalendar });
})();
