// Project Contacts Screen — s-proj-contacts
// Full rewrite with Smart Suggestions, scope tags, mobile-first
(function(){
const { useState, useEffect, useRef, useMemo } = React;

const DEMO_CLIENTS = [];
const DEMO_LOCATIONS = [];

const SCOPE_META = {
  library:  { icon:'📚', label:'ספרייה',   color:'#6b7280', bg:'#f3f4f6' },
  client:   { icon:'🏢', label:'לקוח',     color:'#1d4ed8', bg:'#eff6ff' },
  location: { icon:'📍', label:'לוקיישן',  color:'#059669', bg:'#d1fae5' },
  project:  { icon:'📋', label:'פרויקט',   color:'#7c3aed', bg:'#ede9fe' },
  favorite: { icon:'🌟', label:'מועדף',    color:'#d97706', bg:'#fef3c7' },
};

const ROLE_GROUPS = [
  { group:'ניהול ויזמות', roles:['יזם','שותף יזם','מנכ"ל','מנכ"לית','סמנכ"ל כספים','סמנכ"לית שיווק','הנהל"ח','מנהל בינוי','מנהל שיווק','מנהל אחזקה','מנהל פרויקטים','ניהול פרויקט','משכיר'] },
  { group:'אדריכלות ותכנון', roles:['אדריכל','אדריכלים','מודד','קונסטרוקטור','תכנון ורישוי עסקים'] },
  { group:'יועצים', roles:['יועצי בטיחות','יועצי נגישות','יועצי רישוי','יועצי חשמל','יועצי תאורה','יועצי מיזוג אוויר','יועצי אינסטלציה','יועצי סאונד','יועצי אקוסטיקה','יועצי מטבחים','יועצי איטום','יועצי תנועה'] },
  { group:'קבלני ביצוע', roles:['קבלני גמר','קבלני מיזוג אוויר','קבלני חשמל','קבלני אינסטלציה','קבלן בינוי'] },
  { group:'מערכות ומתח נמוך', roles:['תקשורת/מצלמות/מתח נמוך','מצלמות','סאונד','מערכות גילוי אש','מערכות כיבוי אש'] },
  { group:'ציוד ומטבח', roles:['ציוד קירור ומקררים','ציוד מטבח','נירוסטה'] },
  { group:'עבודות גמר וריהוט', roles:['נגרות','מסגרות','במות רמה','תאורה','תאורה ובקרה','שילוט','ריהוט','מידוף'] },
  { group:'אחר', roles:['לקוח','ספק','אחר'] },
];
const ALL_ROLES = ROLE_GROUPS.flatMap(g => g.roles);

const GLOBAL_CONTACTS_KEY = 'ybp_contacts_v1';
// Fallback ל-localStorage cache בלבד; השימוש העיקרי הוא דרך ContactsStore async
const loadGlobalContactsCache = () => {
  try { return JSON.parse(localStorage.getItem(GLOBAL_CONTACTS_KEY) || '[]'); } catch { return []; }
};

// ── Contact Card ──────────────────────────────────────────────────────────────
const ContactCard = ({ contact, onCall, onEmail, onRemove, showScope = true, actionLabel, onAction, compact = false }) => {
  const roleStyle = (() => {
    const r = contact.role || '';
    if (ROLE_GROUPS[0].roles.includes(r)) return { bg:'#fdf4ff', color:'#7c3aed' };
    if (ROLE_GROUPS[1].roles.includes(r)) return { bg:'#fff7ed', color:'#c2410c' };
    if (ROLE_GROUPS[2].roles.includes(r)) return { bg:'#f0fdf4', color:'#15803d' };
    if (ROLE_GROUPS[3].roles.includes(r)) return { bg:'#eff6ff', color:'#1d4ed8' };
    if (ROLE_GROUPS[4].roles.includes(r)) return { bg:'#fef3c7', color:'#b45309' };
    if (ROLE_GROUPS[5].roles.includes(r)) return { bg:'#f0fdf4', color:'#15803d' };
    if (ROLE_GROUPS[6].roles.includes(r)) return { bg:'#fef9c3', color:'#854d0e' };
    return { bg:'#f3f4f6', color:'#374151' };
  })();
  const scopeM = SCOPE_META[contact.is_favorite ? 'favorite' : contact.scope] || SCOPE_META.library;

  return (
    <div style={{
      background:'#fff', border:'1px solid #e5e7eb', borderRadius:10,
      padding: compact ? '10px 12px' : '14px 14px',
      display:'flex', alignItems:'center', gap:12,
      transition:'box-shadow .15s',
    }}
      onMouseEnter={e => e.currentTarget.style.boxShadow='0 2px 8px rgba(0,0,0,0.08)'}
      onMouseLeave={e => e.currentTarget.style.boxShadow='none'}>

      {/* Avatar */}
      <div style={{ width:compact?36:42, height:compact?36:42, borderRadius:compact?18:21, background:'#1a2c4a',
        color:'#fff', display:'flex', alignItems:'center', justifyContent:'center',
        fontSize:compact?13:15, fontWeight:700, flexShrink:0 }}>
        {contact.name?.split(' ').map(w=>w[0]).join('').slice(0,2)}
      </div>

      {/* Info */}
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ display:'flex', alignItems:'center', gap:6, flexWrap:'wrap' }}>
          <span style={{ fontSize:compact?13:14, fontWeight:700, color:'#1f2937' }}>{contact.name}</span>
          <span style={{ fontSize:10, fontWeight:700, padding:'2px 7px', borderRadius:10, background:roleStyle.bg, color:roleStyle.color }}>{contact.role}</span>
          {showScope && (
            <span style={{ fontSize:10, fontWeight:700, padding:'2px 7px', borderRadius:10, background:scopeM.bg, color:scopeM.color }}>
              {scopeM.icon} {scopeM.label}
            </span>
          )}
        </div>
        {contact.company && <div style={{ fontSize:12, color:'#6b7280', marginTop:2 }}>{contact.company}</div>}
        {!compact && <div style={{ fontSize:11, color:'#9ca3af', marginTop:2 }}>{contact.phone}</div>}
      </div>

      {/* Actions */}
      <div style={{ display:'flex', gap:6, flexShrink:0 }}>
        {onCall && (
          <a href={'tel:'+contact.phone} style={{ width:32, height:32, borderRadius:8, border:'1px solid #e5e7eb', background:'#f9fafb', display:'flex', alignItems:'center', justifyContent:'center', textDecoration:'none', fontSize:14 }} title="התקשר">📞</a>
        )}
        {onEmail && (
          <a href={'mailto:'+contact.email} style={{ width:32, height:32, borderRadius:8, border:'1px solid #e5e7eb', background:'#f9fafb', display:'flex', alignItems:'center', justifyContent:'center', textDecoration:'none', fontSize:14 }} title="שלח מייל">✉️</a>
        )}
        {onAction && (
          <button onClick={() => onAction(contact)} style={{ padding:'5px 12px', borderRadius:7, border:'none', background:'#1a2c4a', color:'#fff', fontSize:11, fontWeight:700, cursor:'pointer', fontFamily:'inherit', whiteSpace:'nowrap' }}>{actionLabel}</button>
        )}
        {onRemove && (
          <button onClick={() => onRemove(contact.id)} style={{ width:32, height:32, borderRadius:8, border:'1px solid #fecaca', background:'#fff', color:'#dc2626', fontSize:14, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }} title="הסר">✕</button>
        )}
      </div>
    </div>
  );
};

// ── Smart Suggestions ─────────────────────────────────────────────────────────
const SmartSuggestions = ({ project, assignedIds, onAdd, globalContacts = [] }) => {
  const [open, setOpen] = useState(true);
  const client = DEMO_CLIENTS.find(c => c.id === project.client_id);
  const location = DEMO_LOCATIONS.find(l => l.id === project.location_id);

  const clientContacts = globalContacts.filter(c => c.scope === 'client' && c.scope_id === project.client_id && !assignedIds.includes(c.id));
  const locationContacts = globalContacts.filter(c => c.scope === 'location' && c.scope_id === project.location_id && !assignedIds.includes(c.id));
  const favoriteContacts = globalContacts.filter(c => c.is_favorite && !assignedIds.includes(c.id));

  const total = clientContacts.length + locationContacts.length + favoriteContacts.length;
  if (total === 0) return null;

  return (
    <div style={{ background:'#fafbfc', border:'1px solid #e5e7eb', borderRadius:12, overflow:'hidden', marginBottom:16 }}>
      <button onClick={() => setOpen(!open)} style={{
        width:'100%', padding:'12px 16px', background:'transparent', border:'none', cursor:'pointer',
        display:'flex', alignItems:'center', gap:8, fontFamily:'inherit',
      }}>
        <span style={{ fontSize:14, fontWeight:700, color:'#1f2937', flex:1, textAlign:'right' }}>
          💡 הצעות חכמות לפרויקט זה
        </span>
        <span style={{ fontSize:11, color:'#9ca3af', background:'#e5e7eb', padding:'2px 8px', borderRadius:10, fontWeight:600 }}>{total}</span>
        <span style={{ color:'#9ca3af', fontSize:12 }}>{open ? '▲' : '▼'}</span>
      </button>

      {open && (
        <div style={{ padding:'0 16px 14px', display:'flex', flexDirection:'column', gap:16 }}>

          {clientContacts.length > 0 && client && (
            <div>
              <div style={{ fontSize:11, fontWeight:700, color:'#1d4ed8', marginBottom:8, display:'flex', alignItems:'center', gap:5 }}>
                🏢 מאנשי הקשר של {client.name} ({clientContacts.length})
              </div>
              <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
                {clientContacts.map(c => (
                  <ContactCard key={c.id} contact={c} compact onCall onEmail onAction={onAdd} actionLabel="+ הוסף"/>
                ))}
              </div>
            </div>
          )}

          {locationContacts.length > 0 && location && (
            <div>
              <div style={{ fontSize:11, fontWeight:700, color:'#059669', marginBottom:8, display:'flex', alignItems:'center', gap:5 }}>
                📍 מאנשי הקשר של {location.name} ({locationContacts.length})
              </div>
              <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
                {locationContacts.map(c => (
                  <ContactCard key={c.id} contact={c} compact onCall onEmail onAction={onAdd} actionLabel="+ הוסף"/>
                ))}
              </div>
            </div>
          )}

          {favoriteContacts.length > 0 && (
            <div>
              <div style={{ fontSize:11, fontWeight:700, color:'#d97706', marginBottom:8, display:'flex', alignItems:'center', gap:5 }}>
                🌟 מהמועדפים שלי ({favoriteContacts.length})
              </div>
              <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
                {favoriteContacts.map(c => (
                  <ContactCard key={c.id} contact={c} compact onCall onEmail onAction={onAdd} actionLabel="+ הוסף"/>
                ))}
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
};

// ── Search & Add modal ────────────────────────────────────────────────────────
const SearchAddModal = ({ assignedIds, onAdd, onClose, globalContacts = [] }) => {
  const [query, setQuery] = useState('');
  const [showNewForm, setShowNewForm] = useState(false);
  const [newName, setNewName] = useState('');
  const [newPhone, setNewPhone] = useState('');
  const [newRole, setNewRole] = useState('');
  const [newCompany, setNewCompany] = useState('');
  const inputRef = useRef(null);
  const [lastAdded, setLastAdded] = useState(null);

  useEffect(() => { inputRef.current?.focus(); }, []);

  const handleAdd = (c) => {
    onAdd(c);
    setQuery('');
    setLastAdded(c.name || '');
    setTimeout(() => setLastAdded(null), 2000);
    setTimeout(() => inputRef.current?.focus(), 0);
  };

  const results = useMemo(() => {
    if (!query.trim()) return [];
    const q = query.toLowerCase();
    return globalContacts.filter(c =>
      !assignedIds.includes(c.id) &&
      (c.name?.toLowerCase().includes(q) || c.company?.toLowerCase().includes(q) || c.role?.toLowerCase().includes(q))
    ).slice(0, 8);
  }, [query, assignedIds, globalContacts]);

  return (
    <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.5)', zIndex:9999, display:'flex', alignItems:'flex-start', justifyContent:'center', paddingTop:60 }}
      onClick={e => e.target === e.currentTarget && onClose()}>
      <div style={{ background:'#fff', borderRadius:14, width:'min(540px, 95vw)', maxHeight:'80vh', overflow:'hidden', direction:'rtl', fontFamily:'Assistant,sans-serif', display:'flex', flexDirection:'column', boxShadow:'0 20px 60px rgba(0,0,0,0.3)' }}>

        {/* Search header */}
        <div style={{ padding:'14px 16px', borderBottom:'1px solid #e5e7eb' }}>
          <div style={{ display:'flex', alignItems:'center', gap:10, background:'#f9fafb', borderRadius:8, padding:'8px 12px', border:'1px solid #e5e7eb' }}>
            <span style={{ fontSize:16 }}>🔍</span>
            <input ref={inputRef} value={query} onChange={e => setQuery(e.target.value)}
              placeholder="חפש לפי שם, חברה, תפקיד..."
              style={{ flex:1, border:'none', background:'transparent', fontSize:14, fontFamily:'inherit', outline:'none', direction:'rtl' }}/>
            {query && <button onClick={() => setQuery('')} style={{ background:'none', border:'none', cursor:'pointer', color:'#9ca3af', fontSize:16 }}>✕</button>}
          </div>
        </div>

        {/* Results */}
        <div style={{ flex:1, overflowY:'auto', padding:'10px 16px', display:'flex', flexDirection:'column', gap:6 }}>
          {!query && !showNewForm && (
            <div style={{ textAlign:'center', padding:'30px 0', color:'#9ca3af' }}>
              <div style={{ fontSize:32, marginBottom:8 }}>🔍</div>
              <div style={{ fontSize:14 }}>התחל להקליד לחיפוש</div>
            </div>
          )}

          {results.map(c => (
            <ContactCard key={c.id} contact={c} onCall onEmail onAction={handleAdd} actionLabel="+ הוסף" showScope/>
          ))}

          {query && results.length === 0 && !showNewForm && (
            <div style={{ textAlign:'center', padding:'24px 0' }}>
              <div style={{ fontSize:13, color:'#6b7280', marginBottom:12 }}>לא נמצא "{query}"</div>
              <button onClick={() => { setShowNewForm(true); setNewName(query); }} style={{
                padding:'9px 20px', borderRadius:7, border:'none', background:'#1a2c4a',
                color:'#fff', fontSize:13, fontWeight:700, cursor:'pointer', fontFamily:'inherit',
              }}>+ צור איש קשר חדש</button>
            </div>
          )}

          {showNewForm && (
            <div style={{ background:'#fafbfc', border:'1px solid #e5e7eb', borderRadius:10, padding:14, display:'flex', flexDirection:'column', gap:10 }}>
              <div style={{ fontSize:13, fontWeight:700, color:'#1f2937' }}>יצירת איש קשר חדש</div>
              <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:8 }}>
                <div>
                  <label style={{ fontSize:11, fontWeight:700, color:'#6b7280', display:'block', marginBottom:3 }}>שם מלא *</label>
                  <input value={newName} onChange={e=>setNewName(e.target.value)}
                    style={{ width:'100%', padding:'7px 10px', border:'1px solid #e5e7eb', borderRadius:6, fontSize:13, fontFamily:'inherit', boxSizing:'border-box' }}/>
                </div>
                <div>
                  <label style={{ fontSize:11, fontWeight:700, color:'#6b7280', display:'block', marginBottom:3 }}>טלפון</label>
                  <input value={newPhone} onChange={e=>setNewPhone(e.target.value)} placeholder="05X-XXXXXXX"
                    style={{ width:'100%', padding:'7px 10px', border:'1px solid #e5e7eb', borderRadius:6, fontSize:13, fontFamily:'inherit', boxSizing:'border-box' }}/>
                </div>
                <div>
                  <label style={{ fontSize:11, fontWeight:700, color:'#6b7280', display:'block', marginBottom:3 }}>תפקיד</label>
                  <RoleInput value={newRole} onChange={setNewRole}/>
                </div>
                <div>
                  <label style={{ fontSize:11, fontWeight:700, color:'#6b7280', display:'block', marginBottom:3 }}>חברה</label>
                  <input value={newCompany} onChange={e=>setNewCompany(e.target.value)}
                    style={{ width:'100%', padding:'7px 10px', border:'1px solid #e5e7eb', borderRadius:6, fontSize:13, fontFamily:'inherit', boxSizing:'border-box' }}/>
                </div>
              </div>
              <div style={{ display:'flex', gap:8 }}>
                <button onClick={() => {
                  if (!newName.trim()) return;
                  const newContact = { id:'c-new-'+Date.now(), name:newName, role:newRole, company:newCompany, phone:newPhone, email:'', scope:'project', is_favorite:false, active:true };
                  handleAdd(newContact);
                }} style={{ flex:1, padding:'9px', borderRadius:6, border:'none', background:'#1a2c4a', color:'#fff', fontSize:13, fontWeight:700, cursor:'pointer' }}>שמור ושייך</button>
                <button onClick={() => setShowNewForm(false)} style={{ padding:'9px 14px', borderRadius:6, border:'1px solid #e5e7eb', background:'#fff', fontSize:13, cursor:'pointer' }}>ביטול</button>
              </div>
            </div>
          )}
        </div>

        {lastAdded && <div style={{padding:'8px 16px', background:'#f0fdf4', color:'#15803d', fontSize:13, fontWeight:700}}>✓ {lastAdded} נוסף לפרויקט</div>}

        {/* Footer */}
        <div style={{ padding:'10px 16px', borderTop:'1px solid #f3f4f6', display:'flex', justifyContent:'space-between', alignItems:'center' }}>
          {!showNewForm && query && results.length > 0 && (
            <button onClick={() => setShowNewForm(true)} style={{ background:'transparent', border:'none', color:'#1d4ed8', fontSize:12, fontWeight:600, cursor:'pointer', fontFamily:'inherit' }}>+ צור איש קשר חדש</button>
          )}
          <button onClick={onClose} style={{ marginRight:'auto', padding:'7px 16px', borderRadius:6, border:'1px solid #e5e7eb', background:'#fff', fontSize:13, cursor:'pointer', fontFamily:'inherit' }}>סגור</button>
        </div>
      </div>
    </div>
  );
};

const RoleInput = ({ value, onChange }) => {
  const [open, setOpen] = useState(false);
  const [q, setQ] = useState(value);
  const filtered = useMemo(() => {
    if (!q.trim()) return ROLE_GROUPS;
    const lq = q.toLowerCase();
    return ROLE_GROUPS.map(g => ({ ...g, roles: g.roles.filter(r => r.includes(lq)) })).filter(g => g.roles.length > 0);
  }, [q]);
  return (
    <div style={{ position:'relative' }}>
      <input value={q} onChange={e => { setQ(e.target.value); onChange(e.target.value); setOpen(true); }}
        onFocus={() => setOpen(true)} onBlur={() => setTimeout(() => setOpen(false), 150)}
        placeholder="חפש או הקלד תפקיד..."
        style={{ width:'100%', padding:'7px 10px', border:'1px solid #e5e7eb', borderRadius:6, fontSize:13, fontFamily:'inherit', boxSizing:'border-box' }}/>
      {open && filtered.length > 0 && (
        <div style={{ position:'absolute', top:'100%', right:0, left:0, background:'#fff', border:'1px solid #e5e7eb', borderRadius:8, boxShadow:'0 4px 16px rgba(0,0,0,0.12)', zIndex:999, maxHeight:220, overflowY:'auto', direction:'rtl' }}>
          {filtered.map(g => (
            <div key={g.group}>
              <div style={{ padding:'5px 10px', fontSize:10, fontWeight:700, color:'#9ca3af', background:'#f9fafb', letterSpacing:0.3 }}>{g.group}</div>
              {g.roles.map(r => (
                <div key={r} onClick={() => { setQ(r); onChange(r); setOpen(false); }}
                  style={{ padding:'7px 14px', fontSize:13, cursor:'pointer', color:'#1f2937' }}
                  onMouseEnter={e => e.currentTarget.style.background='#f3f4f6'}
                  onMouseLeave={e => e.currentTarget.style.background='transparent'}>
                  {r}
                </div>
              ))}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

// ── Main Component ────────────────────────────────────────────────────────────
const ProjContactsScreen = ({ projectId, onBack }) => {
  const project = useMemo(() => {
    return YBP_DATA?.projects?.find(p => p.id === projectId) || YBP_DATA?.projects?.[0] || {};
  }, [projectId]);

  const client = DEMO_CLIENTS.find(c => c.id === project?.client_id);
  const location = DEMO_LOCATIONS.find(l => l.id === project?.location_id);

  const [assignedIds, setAssignedIds] = useState([]);
  const [globalContacts, setGlobalContacts] = useState(() => loadGlobalContactsCache());
  const [showSearch, setShowSearch] = useState(false);
  const [search, setSearch] = useState('');
  const [loading, setLoading] = useState(true);
  const [busy, setBusy] = useState(false);

  // טעינה ראשונית מ-Supabase (אחרי migration אוטומטי אם רלוונטי)
  useEffect(() => {
    if (!window.ContactsStore) { setLoading(false); return; }
    let cancelled = false;
    (async () => {
      try {
        await window.ContactsStore.migrateLocalStorageIfNeeded();
        const [globals, projectScoped] = await Promise.all([
          window.ContactsStore.listAll(),
          window.ContactsStore.listForProject(projectId),
        ]);
        if (cancelled) return;
        setGlobalContacts(globals);
        setAssignedIds(projectScoped.map(c => c.id));
      } catch (e) {
        console.warn('[ProjContactsScreen] load failed:', e.message);
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => { cancelled = true; };
  }, [projectId]);

  const assignedContacts = useMemo(() => {
    return assignedIds.map(id => globalContacts.find(c => c.id === id)).filter(Boolean);
  }, [assignedIds, globalContacts]);

  const filteredAssigned = useMemo(() => {
    if (!search.trim()) return assignedContacts;
    const q = search.toLowerCase();
    return assignedContacts.filter(c => (c.name||'').toLowerCase().includes(q) || (c.company||'').toLowerCase().includes(q));
  }, [assignedContacts, search]);

  const addContact = async (contact) => {
    if (!window.ContactsStore) return;
    setBusy(true);
    try {
      let target = contact;
      // איש קשר חדש שנוצר במודאל ("c-new-...") — קודם ליצור ב-Supabase
      if (!contact.id || String(contact.id).startsWith('c-new-')) {
        target = await window.ContactsStore.create({ ...contact, id: undefined });
        // רענון רשימה גלובלית
        const globals = await window.ContactsStore.listAll();
        setGlobalContacts(globals);
      }
      if (assignedIds.includes(target.id)) return;
      // optimistic UI
      setAssignedIds(prev => [...prev, target.id]);
      await window.ContactsStore.attachToProject(projectId, target.id);
      // החלון נשאר פתוח — המשתמש סוגר ידנית
    } catch (e) {
      alert('שגיאה בשיוך איש קשר: ' + (e.message || 'unknown'));
      // refresh ל-recovery
      try {
        const projectScoped = await window.ContactsStore.listForProject(projectId);
        setAssignedIds(projectScoped.map(c => c.id));
      } catch {}
    } finally { setBusy(false); }
  };

  const removeContact = async (id) => {
    if (!window.ContactsStore) return;
    const prev = assignedIds;
    setAssignedIds(prev.filter(i => i !== id)); // optimistic
    try {
      await window.ContactsStore.detachFromProject(projectId, id);
    } catch (e) {
      alert('שגיאה בהסרת איש קשר: ' + (e.message || 'unknown'));
      setAssignedIds(prev); // rollback
    }
  };

  const handleExportExcel = () => {
    if (!window.ContactsStore) return;
    const rows = assignedContacts.map(c => ({ ...c, _projectName: project?.name }));
    const safeName = (project?.name || projectId).replace(/[\\/:*?"<>|]/g, '_');
    const date = new Date().toISOString().slice(0,10);
    window.ContactsStore.exportToExcel(rows, `YBP_אנשי_קשר_${safeName}_${date}.xlsx`);
  };

  return (
    <div style={{ minHeight:'100%', background:'#f6f7f9', fontFamily:'Assistant,sans-serif', direction:'rtl' }}>

      {/* Header */}
      <header style={{ background:'#1a2c4a', color:'#fff', padding:'14px 16px', position:'sticky', top:0, zIndex:10 }}>
        <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:8 }}>
          <button onClick={onBack} style={{ background:'rgba(255,255,255,0.12)', border:'1px solid rgba(255,255,255,0.2)', color:'#fff', width:34, height:34, borderRadius:7, display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', flexShrink:0 }}>
            <Icon name="chevron" size={16}/>
          </button>
          <div style={{ flex:1 }}>
            <div style={{ fontSize:11, opacity:0.65, marginBottom:1 }}>{project?.name}</div>
            <div style={{ fontSize:16, fontWeight:700 }}>👥 דף קשר</div>
          </div>
          <div style={{ display:'flex', gap:6, alignItems:'center' }}>
            <button onClick={handleExportExcel} disabled={busy || assignedContacts.length===0} title="ייצא לקובץ Excel" style={{
              background:'rgba(255,255,255,0.1)', color:'#fff', border:'1px solid rgba(255,255,255,0.18)',
              padding:'7px 11px', borderRadius:6, fontSize:11.5, fontWeight:600,
              cursor: busy||assignedContacts.length===0?'not-allowed':'pointer', fontFamily:'inherit', opacity: busy||assignedContacts.length===0?0.5:1,
            }}>📥 Excel</button>
            <button onClick={() => setShowSearch(true)} disabled={busy} style={{ background:'#b5a882', color:'#1a2c4a', border:'none', padding:'8px 16px', borderRadius:7, fontSize:13, fontWeight:800, cursor:busy?'not-allowed':'pointer', fontFamily:'inherit', display:'flex', alignItems:'center', gap:5, opacity:busy?0.5:1 }}>
              <span>+</span> הוסף
            </button>
          </div>
        </div>

        {/* Context tags */}
        <div style={{ display:'flex', gap:6 }}>
          {client && <span style={{ fontSize:11, background:'rgba(255,255,255,0.15)', padding:'3px 10px', borderRadius:10, fontWeight:600 }}>🏢 {client.name}</span>}
          {location && <span style={{ fontSize:11, background:'rgba(255,255,255,0.15)', padding:'3px 10px', borderRadius:10, fontWeight:600 }}>📍 {location.name}</span>}
          <span style={{ fontSize:11, background:'rgba(255,255,255,0.1)', padding:'3px 10px', borderRadius:10 }}>{assignedIds.length} משויכים</span>
        </div>
      </header>

      <div style={{ maxWidth:640, margin:'0 auto', padding:'16px' }}>

        {/* Smart Suggestions */}
        <SmartSuggestions project={project} assignedIds={assignedIds} onAdd={addContact} globalContacts={globalContacts}/>

        {/* Assigned contacts */}
        <div>
          <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:10 }}>
            <span style={{ fontSize:14, fontWeight:700, color:'#1f2937', flex:1 }}>
              אנשי קשר משויכים ({assignedIds.length})
            </span>
          </div>

          {/* Search filter */}
          {assignedContacts.length > 4 && (
            <div style={{ marginBottom:10, background:'#fff', borderRadius:8, border:'1px solid #e5e7eb', padding:'7px 12px', display:'flex', alignItems:'center', gap:8 }}>
              <span style={{ color:'#9ca3af', fontSize:14 }}>🔍</span>
              <input value={search} onChange={e => setSearch(e.target.value)}
                placeholder="סנן מהרשימה..."
                style={{ flex:1, border:'none', background:'transparent', fontSize:13, fontFamily:'inherit', outline:'none' }}/>
            </div>
          )}

          {/* Loading state */}
          {loading && (
            <div style={{ textAlign:'center', padding:'30px', color:'#9ca3af', fontSize:13 }}>טוען אנשי קשר...</div>
          )}

          {/* Empty state */}
          {!loading && assignedContacts.length === 0 && (
            <div style={{ textAlign:'center', padding:'40px 20px', background:'#fff', borderRadius:12, border:'1px dashed #d1d5db' }}>
              <div style={{ fontSize:40, marginBottom:10 }}>👥</div>
              <div style={{ fontSize:15, fontWeight:600, color:'#374151', marginBottom:6 }}>טרם שויכו אנשי קשר לפרויקט זה</div>
              <div style={{ fontSize:13, color:'#9ca3af', marginBottom:16 }}>הוסף מהצעות חכמות למעלה, או חפש במאגר</div>
              <button onClick={() => setShowSearch(true)} disabled={busy} style={{ padding:'9px 22px', borderRadius:7, border:'none', background:'#1a2c4a', color:'#fff', fontSize:13, fontWeight:700, cursor:busy?'not-allowed':'pointer', fontFamily:'inherit', opacity:busy?0.5:1 }}>+ הוסף איש קשר</button>
            </div>
          )}

          {/* Contact list */}
          <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
            {filteredAssigned.map(c => (
              <ContactCard key={c.id} contact={c} onCall onEmail onRemove={removeContact} showScope/>
            ))}
          </div>

          {search && filteredAssigned.length === 0 && (
            <div style={{ textAlign:'center', padding:'20px', color:'#9ca3af', fontSize:13 }}>לא נמצאו תוצאות עבור "{search}"</div>
          )}
        </div>
      </div>

      {/* Search Modal */}
      {showSearch && (
        <SearchAddModal
          assignedIds={assignedIds}
          onAdd={addContact}
          onClose={() => setShowSearch(false)}
          globalContacts={globalContacts}
        />
      )}
    </div>
  );
};

window.ProjContactsScreen = ProjContactsScreen;
})();
