// ContactsScreen — s-contacts
// 4 tabs: ספרייה / לקוחות / לוקיישנים / מועדפים
(function(){
const { useState, useEffect, useRef, useMemo } = React;

// ── Shared data (mirrors proj-contacts) ───────────────────────────────────────
const DEMO_CLIENTS = [
  { id:'client_roladin',    name:'רולדין',      emoji:'🥐', category:'מזון ומסעדות' },
  { id:'client_pizza',      name:'פיצה האט',    emoji:'🍕', category:'מזון ומסעדות' },
  { id:'client_mcdonalds',  name:'מקדונלדס',    emoji:'🍔', category:'מזון ומסעדות' },
  { id:'client_wework',     name:'WeWork',       emoji:'🏢', category:'משרדים' },
  { id:'client_superpharm', name:'סופר-פארם',   emoji:'💊', category:'קמעונאות' },
];

const DEMO_LOCATIONS = [
  { id:'loc_natbag',    name:'נתב"ג טרמינל 3',   emoji:'✈️', city:'לוד' },
  { id:'loc_ayalon',   name:'קניון איילון',       emoji:'🛍️', city:'רמת גן' },
  { id:'loc_tel_aviv', name:'תל אביב מרכז',       emoji:'🏙️', city:'תל אביב' },
  { id:'loc_haifa',    name:'קניון חיפה',          emoji:'🌊', city:'חיפה' },
  { id:'loc_beer',     name:'באר שבע גרנד',        emoji:'🏜️', city:'באר שבע' },
];

// ── Custom clients / locations (localStorage — cross-device sync not required for config)
const CUSTOM_CLIENTS_KEY = 'ybp_custom_clients';
const CUSTOM_LOCS_KEY    = 'ybp_custom_locations';
const loadCustomClients   = () => { try { return JSON.parse(localStorage.getItem(CUSTOM_CLIENTS_KEY)||'[]'); } catch { return []; } };
const saveCustomClients   = (list) => { try { localStorage.setItem(CUSTOM_CLIENTS_KEY, JSON.stringify(list)); } catch {} };
const loadCustomLocs      = () => { try { return JSON.parse(localStorage.getItem(CUSTOM_LOCS_KEY)||'[]'); } catch { return []; } };
const saveCustomLocs      = (list) => { try { localStorage.setItem(CUSTOM_LOCS_KEY, JSON.stringify(list)); } catch {} };

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 ROLE_COLOR = (role) => {
  if (ROLE_GROUPS[0].roles.includes(role)) return { bg:'#fdf4ff', color:'#7c3aed' };
  if (ROLE_GROUPS[1].roles.includes(role)) return { bg:'#fff7ed', color:'#c2410c' };
  if (ROLE_GROUPS[2].roles.includes(role)) return { bg:'#f0fdf4', color:'#15803d' };
  if (ROLE_GROUPS[3].roles.includes(role)) return { bg:'#eff6ff', color:'#1d4ed8' };
  if (ROLE_GROUPS[4].roles.includes(role)) return { bg:'#fef3c7', color:'#b45309' };
  if (ROLE_GROUPS[5].roles.includes(role)) return { bg:'#f0fdf4', color:'#15803d' };
  if (ROLE_GROUPS[6].roles.includes(role)) return { bg:'#fef9c3', color:'#854d0e' };
  return { bg:'#f3f4f6', color:'#374151' };
};

// ── Make integration ──────────────────────────────────────────────────────────
function getWebhookUrl(key) {
  try {
    const s = JSON.parse(localStorage.getItem('ybp_settings') || '{}');
    return (s.webhooks || {})[key] || '';
  } catch { return ''; }
}

function getSecurityKey() {
  try {
    const s = JSON.parse(localStorage.getItem('ybp_settings') || '{}');
    return (s.webhooks || {})._securityKey || '';
  } catch { return ''; }
}

function getGoogleClientId() {
  try {
    const s = JSON.parse(localStorage.getItem('ybp_settings') || '{}');
    return s.googleClientId || '40648614185-quk0dilq1difn209jdrrfqi2nq5lif2k.apps.googleusercontent.com';
  } catch { return '40648614185-quk0dilq1difn209jdrrfqi2nq5lif2k.apps.googleusercontent.com'; }
}

function parseSheetsContacts(data) {
  // Support two response formats from Make:
  // 1. Google Sheets API: { values: [[header], [row], ...] }
  // 2. Direct array of objects: [{שם:"...", חברה:"...", ...}, ...]
  let rows = (data && data.values) || [];

  if (rows.length === 0 && Array.isArray(data)) {
    // Format 2: array of objects — convert to rows
    const allKeys = Object.keys(data[0] || {});
    rows = [allKeys, ...data.map(obj => allKeys.map(k => obj[k] ?? ''))];
  }

  if (rows.length < 2) return null;

  // header row — detect column positions by name (case-insensitive)
  const hdr = rows[0].map(h => (h || '').toString().toLowerCase().trim());
  const col = (names) => {
    for (const n of names) { const i = hdr.indexOf(n); if (i >= 0) return i; }
    return -1;
  };

  // Column mapping — matches the YBP Contacts DB sheet: שם|חברה|תפקיד|נייד|Email|משרד
  const iId      = col(['id', 'מזהה']);
  const iName    = col(['שם', 'name', 'שם מלא']);
  const iCompany = col(['חברה', 'company', 'שם חברה']);
  const iRole    = col(['תפקיד', 'role', 'תחום']);
  const iPhone   = col(['נייד', 'טלפון', 'phone', 'mobile']);
  const iEmail   = col(['email', 'מייל', 'אימייל']);
  const iOffice  = col(['משרד', 'office', 'טלפון משרד']);
  const iNotes   = col(['הערות', 'notes']);
  const iScope   = col(['scope', 'סוג']);
  const iFav     = col(['מועדף', 'favorite', 'is_favorite']);

  const contacts = [];
  const seen = new Set();
  for (let i = 1; i < rows.length; i++) {
    const r = rows[i];
    const name = (iName >= 0 ? r[iName] : '') || '';
    if (!name.trim()) continue;
    const id = (iId >= 0 && r[iId]) ? String(r[iId]).trim() : 'gs-' + i;
    if (seen.has(id)) continue;
    seen.add(id);
    const office = (iOffice >= 0 ? r[iOffice] : '') || '';
    const notes  = (iNotes  >= 0 ? r[iNotes]  : '') || '';
    contacts.push({
      id,
      name: name.trim(),
      company: (iCompany >= 0 ? r[iCompany] : '') || '',
      role:    (iRole    >= 0 ? r[iRole]    : '') || '',
      phone:   (iPhone   >= 0 ? r[iPhone]   : '') || '',
      email:   (iEmail   >= 0 ? r[iEmail]   : '') || '',
      notes:   [notes, office ? `משרד: ${office}` : ''].filter(Boolean).join(' | '),
      scope:   (iScope   >= 0 && r[iScope]) ? String(r[iScope]) : 'library',
      scope_id: null,
      is_favorite: (iFav >= 0 && r[iFav]) ? String(r[iFav]).toLowerCase() === 'true' : false,
      active: true,
    });
  }
  return contacts.length ? contacts : null;
}

async function loadContactsFromMake() {
  const url = getWebhookUrl('PLACEHOLDER_LOAD_CONTACTS');
  if (!url) return null;
  try {
    const resp = await fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ action: 'list', _sk: getSecurityKey() }),
    });
    if (!resp.ok) throw new Error('HTTP ' + resp.status);
    const data = await resp.json();
    return parseSheetsContacts(data);
  } catch (e) {
    console.warn('[YBP] loadContactsFromMake failed:', e.message);
    return null;
  }
}

async function syncContactToMake(action, payload) {
  const KEY = { save: 'PLACEHOLDER_SAVE_CONTACT', update: 'PLACEHOLDER_UPDATE_CONTACT', delete: 'PLACEHOLDER_DELETE_CONTACT' };
  const url = getWebhookUrl(KEY[action]);
  if (!url) return;
  try {
    await fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ ...payload, _sk: getSecurityKey() }),
    });
  } catch (e) {
    console.warn('[YBP] syncContactToMake(' + action + ') failed:', e.message);
  }
}

// ── Storage ───────────────────────────────────────────────────────────────────
const STORAGE_KEY = 'ybp_contacts_v1';

const DEMO_CONTACT_IDS = new Set(['c1','c2','c3','c4','c5','c6','c7','c8','c9','c10','c11','c12','c13','c14','c15']);

const loadContacts = () => {
  try {
    const raw = localStorage.getItem(STORAGE_KEY);
    if (raw) {
      const contacts = JSON.parse(raw);
      // purge demo contacts on first load
      const filtered = contacts.filter(c => !DEMO_CONTACT_IDS.has(c.id));
      if (filtered.length !== contacts.length) {
        try { localStorage.setItem(STORAGE_KEY, JSON.stringify(filtered)); } catch {}
      }
      return filtered;
    }
  } catch {}
  return [];
};
const saveContacts = (contacts) => {
  try { localStorage.setItem(STORAGE_KEY, JSON.stringify(contacts)); } catch {}
};

// ── Helpers ───────────────────────────────────────────────────────────────────
const initials = (name) => name?.split(' ').map(w => w[0]).join('').slice(0,2) || '?';

const AVATAR_COLORS = ['#1a2c4a','#2563eb','#059669','#7c3aed','#c2410c','#b45309','#0369a1'];
const avatarColor = (name) => AVATAR_COLORS[(name?.charCodeAt(0) || 0) % AVATAR_COLORS.length];

// ── Sub-components ────────────────────────────────────────────────────────────

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:'8px 10px', border:'1px solid #e5e7eb', borderRadius:7, fontSize:13, fontFamily:'inherit', boxSizing:'border-box', outline:'none' }}/>
      {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:200, 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} onMouseDown={() => { 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>
  );
};

// Full contact card
const ContactCard = ({ contact, onToggleFavorite, onEdit, onDelete, onOpen, compact = false }) => {
  const rc = ROLE_COLOR(contact.role);
  return (
    <div style={{
      background:'#fff', border:'1px solid #e5e7eb', borderRadius:10,
      padding: compact ? '10px 12px' : '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.07)'}
      onMouseLeave={e => e.currentTarget.style.boxShadow='none'}
      onClick={() => onOpen?.(contact)}>

      {/* Avatar */}
      <div style={{
        width: compact?36:44, height: compact?36:44, borderRadius:'50%',
        background: avatarColor(contact.name), color:'#fff',
        display:'flex', alignItems:'center', justifyContent:'center',
        fontSize: compact?13:16, fontWeight:700, flexShrink:0,
        letterSpacing:-0.5,
      }}>
        {initials(contact.name)}
      </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:rc.bg, color:rc.color, flexShrink:0 }}>{contact.role}</span>
        </div>
        {contact.company && <div style={{ fontSize:12, color:'#6b7280', marginTop:1 }}>{contact.company}</div>}
        {!compact && (contact.phone || contact.office_phone) && (
          <div style={{ fontSize:11, color:'#9ca3af', marginTop:2, direction:'ltr', textAlign:'right' }}>
            {contact.phone && <span>📱 {contact.phone}</span>}
            {contact.phone && contact.office_phone && <span> · </span>}
            {contact.office_phone && <span>🏢 {contact.office_phone}</span>}
          </div>
        )}
        {!compact && (contact.email || contact.office_email) && (
          <div style={{ fontSize:11, color:'#9ca3af', marginTop:1, direction:'ltr', textAlign:'right' }}>
            {contact.email && <span>{contact.email}</span>}
            {contact.email && contact.office_email && <span> · </span>}
            {contact.office_email && <span style={{ color:'#a78bfa' }}>{contact.office_email}</span>}
          </div>
        )}
        {!compact && contact.notes && <div style={{ fontSize:11, color:'#b5a882', marginTop:2, fontStyle:'italic' }}>{contact.notes}</div>}
      </div>

      {/* Actions */}
      <div style={{ display:'flex', gap:5, flexShrink:0, alignItems:'center' }}>
        {contact.phone && (
          <a href={`tel:${contact.phone}`} style={{ width:30, height:30, borderRadius:7, border:'1px solid #e5e7eb', background:'#f9fafb', display:'flex', alignItems:'center', justifyContent:'center', textDecoration:'none', fontSize:13 }} title="התקשר">📞</a>
        )}
        {contact.email && (
          <a href={`mailto:${contact.email}`} style={{ width:30, height:30, borderRadius:7, border:'1px solid #e5e7eb', background:'#f9fafb', display:'flex', alignItems:'center', justifyContent:'center', textDecoration:'none', fontSize:13 }} title="שלח מייל">✉️</a>
        )}
        {onToggleFavorite && (
          <button onClick={() => onToggleFavorite(contact.id)} title={contact.is_favorite ? 'הסר ממועדפים' : 'הוסף למועדפים'}
            style={{ width:30, height:30, borderRadius:7, border:'1px solid #e5e7eb', background:'#f9fafb', display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', fontSize:14, color: contact.is_favorite ? '#d97706' : '#d1d5db' }}>
            {contact.is_favorite ? '★' : '☆'}
          </button>
        )}
        {onEdit && (
          <button onClick={() => onEdit(contact)}
            style={{ width:30, height:30, borderRadius:7, border:'1px solid #e5e7eb', background:'#f9fafb', display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', fontSize:13 }} title="ערוך">✏️</button>
        )}
        {onDelete && (
          <button onClick={() => onDelete(contact.id)}
            style={{ width:30, height:30, borderRadius:7, border:'1px solid #fecaca', background:'#fff', display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', fontSize:13, color:'#dc2626' }} title="מחק">✕</button>
        )}
      </div>
    </div>
  );
};

// ── Add / Edit modal ──────────────────────────────────────────────────────────
const ContactModal = ({ contact, onSave, onClose, allContactsList = [] }) => {
  const isEdit = !!contact?.id;
  const [form, setForm] = useState(() => {
    const defaults = {
      name:'', role:'', company:'',
      phone:'', email:'',
      office_phone:'', office_email:'',
      notes:'', scope:'library', scope_id:null, scope_ids:[],
      is_favorite:false, active:true,
    };
    if (!contact) return defaults;
    return {
      ...defaults,
      ...contact,
      scope_ids: Array.isArray(contact.scope_ids) ? [...contact.scope_ids] : [],
    };
  });
  const f = (k, v) => setForm(p => ({ ...p, [k]: v }));

  // Auto-scope: יזם / שותף יזם → client (CRM) — only on new contacts
  useEffect(() => {
    if (!isEdit && ['יזם','שותף יזם'].includes(form.role) && form.scope === 'library') {
      setForm(p => ({ ...p, scope: 'client' }));
    }
  }, [form.role]);

  // Custom clients & locations (persisted in localStorage)
  const [customClients, setCustomClients] = useState(loadCustomClients);
  const [customLocs,    setCustomLocs]    = useState(loadCustomLocs);
  // לקוחות אמיתיים מ-Supabase (scope='client') + DEMO_CLIENTS + customClients מ-localStorage
  const allClients = useMemo(() => {
    const fromDb = (allContactsList || [])
      .filter(c => c.scope === 'client' && c.id !== contact?.id)
      .map(c => ({ id: c.id, name: c.name || c.company || '?', emoji: '🏢', category: c.role || 'לקוח' }));
    const demoIds = new Set(DEMO_CLIENTS.map(d => d.id));
    const uniqueFromDb = fromDb.filter(c => !demoIds.has(c.id));
    return [...uniqueFromDb, ...DEMO_CLIENTS, ...customClients];
  }, [allContactsList, customClients, contact?.id]);
  const allLocations = useMemo(() => [...DEMO_LOCATIONS, ...customLocs],    [customLocs]);

  const [newClientInput,   setNewClientInput]   = useState('');
  const [newLocationInput, setNewLocationInput] = useState('');

  const addCustomClient = () => {
    const name = newClientInput.trim();
    if (!name) return;
    const id = 'custom_cl_' + Date.now();
    const updated = [...customClients, { id, name, emoji:'🏢', category:'לקוח' }];
    setCustomClients(updated);
    saveCustomClients(updated);
    const ids = form.scope_ids || [];
    f('scope_ids', [...ids, id]);
    f('scope_id', ids.length === 0 ? id : form.scope_id); // primary = first
    setNewClientInput('');
  };

  const addCustomLocation = () => {
    const name = newLocationInput.trim();
    if (!name) return;
    const id = 'custom_loc_' + Date.now();
    const updated = [...customLocs, { id, name, emoji:'📍', city:'' }];
    setCustomLocs(updated);
    saveCustomLocs(updated);
    f('scope_id', id);
    setNewLocationInput('');
  };

  // ── Google Contacts — live autocomplete ────────────────────────────────────
  const [gcOpen,        setGcOpen]        = useState(false);
  const [gcQuery,       setGcQuery]       = useState('');
  const [gcAllContacts, setGcAllContacts] = useState([]);
  const [gcLoading,     setGcLoading]     = useState(false);
  const gcTokenRef = useRef(null);

  const gcFiltered = useMemo(() => {
    const q = gcQuery.trim().toLowerCase();
    if (!q) return gcAllContacts.slice(0, 8);
    return gcAllContacts.filter(p =>
      p.name.toLowerCase().includes(q) ||
      (p.company||'').toLowerCase().includes(q)
    ).slice(0, 12);
  }, [gcAllContacts, gcQuery]);

  const loadAllGcContacts = async (token) => {
    setGcLoading(true);
    setGcAllContacts([]);
    try {
      let all = [];
      let nextPage = null;
      do {
        const url = `https://people.googleapis.com/v1/people/me/connections?personFields=names,phoneNumbers,emailAddresses,organizations&pageSize=1000${nextPage ? '&pageToken=' + nextPage : ''}`;
        const resp = await fetch(url, { headers: { Authorization: 'Bearer ' + token } });
        const data = await resp.json();
        all = [...all, ...(data.connections || [])];
        nextPage = data.nextPageToken || null;
      } while (nextPage);
      setGcAllContacts(all.map(p => ({
        name:    p.names?.[0]?.displayName || '',
        phone:   p.phoneNumbers?.[0]?.canonicalForm || p.phoneNumbers?.[0]?.value || '',
        email:   p.emailAddresses?.[0]?.value || '',
        company: p.organizations?.[0]?.name || '',
      })).filter(p => p.name));
    } catch { setGcAllContacts([]); }
    setGcLoading(false);
  };

  const openGooglePicker = () => {
    if (!window.google?.accounts?.oauth2) { alert('Google API לא זמין — נסה לרענן את הדף'); return; }
    setGcOpen(true);
    if (gcTokenRef.current && gcAllContacts.length > 0) return; // already loaded
    if (gcTokenRef.current) { loadAllGcContacts(gcTokenRef.current); return; }
    const client = window.google.accounts.oauth2.initTokenClient({
      client_id: getGoogleClientId(),
      scope: 'https://www.googleapis.com/auth/contacts.readonly',
      callback: (tr) => {
        if (tr.error) { setGcOpen(false); return; }
        gcTokenRef.current = tr.access_token;
        loadAllGcContacts(tr.access_token);
      },
    });
    client.requestAccessToken({ prompt: '' });
  };

  const selectGcContact = (gc) => {
    if (gc.name)  f('name',  gc.name);
    if (gc.phone) f('phone', gc.phone);
    if (gc.email) f('email', gc.email);
    if (gc.company) f('company', gc.company);
    setGcOpen(false);
    setGcQuery('');
  };

  return (
    <div style={{ position:'fixed', inset:0, background:'rgba(0,0,0,0.5)', zIndex:9999, display:'flex', alignItems:'center', justifyContent:'center', padding:16 }}
      onClick={e => e.target === e.currentTarget && onClose()}>
      <div style={{ background:'#fff', borderRadius:14, width:'min(520px,95vw)', maxHeight:'90vh', overflowY:'auto', direction:'rtl', fontFamily:'Assistant,sans-serif', boxShadow:'0 20px 60px rgba(0,0,0,0.25)' }}>

        {/* Header */}
        <div style={{ padding:'16px 18px 14px', borderBottom:'1px solid #f3f4f6', display:'flex', alignItems:'center', gap:10, position:'sticky', top:0, background:'#fff', borderRadius:'14px 14px 0 0', zIndex:1 }}>
          <div style={{ width:40, height:40, borderRadius:'50%', background:'#1a2c4a', color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', fontSize:16, fontWeight:700 }}>
            {form.name ? initials(form.name) : '?'}
          </div>
          <div style={{ flex:1 }}>
            <div style={{ fontSize:15, fontWeight:700, color:'#1f2937' }}>{isEdit ? 'עריכת איש קשר' : 'איש קשר חדש'}</div>
            <div style={{ fontSize:11, color:'#9ca3af' }}>מאגר אנשי קשר YBP</div>
          </div>
          <button onClick={onClose} style={{ background:'none', border:'none', fontSize:20, cursor:'pointer', color:'#9ca3af', lineHeight:1 }}>✕</button>
        </div>

        {/* Body */}
        <div style={{ padding:18, display:'flex', flexDirection:'column', gap:14 }}>

          {/* Google Contacts — live autocomplete (new contacts only) */}
          {!isEdit && (
            <div style={{ background:'#f0f9ff', border:'1px solid #bae6fd', borderRadius:9, padding:'10px 12px' }}>
              {!gcOpen ? (
                <button onClick={openGooglePicker}
                  style={{ width:'100%', padding:'8px', background:'#fff', border:'1px solid #93c5fd', borderRadius:7, fontSize:12, fontWeight:700, cursor:'pointer', fontFamily:'inherit', color:'#1d4ed8', display:'flex', alignItems:'center', justifyContent:'center', gap:6 }}>
                  <span style={{ fontSize:15 }}>📇</span> ייבא מ-Google Contacts
                </button>
              ) : (
                <div>
                  <div style={{ display:'flex', gap:6, marginBottom:6, alignItems:'center' }}>
                    <input value={gcQuery} onChange={e => setGcQuery(e.target.value)}
                      placeholder={gcLoading ? '⟳ טוען קשרים מ-Google...' : gcAllContacts.length > 0 ? `חפש בין ${gcAllContacts.length} קשרים...` : 'מחכה לטעינה...'}
                      autoFocus
                      style={{ flex:1, padding:'7px 10px', border:'1px solid #93c5fd', borderRadius:7, fontSize:12, fontFamily:'inherit', outline:'none', direction:'rtl' }}/>
                    <button onClick={() => { setGcOpen(false); setGcQuery(''); }}
                      style={{ padding:'7px 10px', background:'#f3f4f6', border:'1px solid #e5e7eb', borderRadius:7, fontSize:12, cursor:'pointer' }}>✕</button>
                  </div>
                  {gcLoading && (
                    <div style={{ textAlign:'center', fontSize:12, color:'#6b7280', padding:'8px' }}>⟳ טוען קשרים מ-Google Contacts...</div>
                  )}
                  {!gcLoading && gcAllContacts.length === 0 && (
                    <div style={{ textAlign:'center', fontSize:12, color:'#9ca3af', padding:'6px' }}>לא נמצאו קשרים</div>
                  )}
                  {!gcLoading && gcAllContacts.length > 0 && gcQuery.trim() && gcFiltered.length === 0 && (
                    <div style={{ textAlign:'center', fontSize:12, color:'#9ca3af', padding:'6px' }}>לא נמצאו תוצאות עבור "{gcQuery}"</div>
                  )}
                  <div style={{ maxHeight:160, overflowY:'auto', display:'flex', flexDirection:'column', gap:4 }}>
                    {gcFiltered.map((gc, i) => (
                      <button key={i} onClick={() => selectGcContact(gc)}
                        style={{ padding:'8px 10px', background:'#fff', border:'1px solid #e5e7eb', borderRadius:7, cursor:'pointer', fontFamily:'inherit', textAlign:'right', display:'flex', flexDirection:'column', gap:2 }}
                        onMouseEnter={e => e.currentTarget.style.background='#eff6ff'}
                        onMouseLeave={e => e.currentTarget.style.background='#fff'}>
                        <span style={{ fontSize:13, fontWeight:700, color:'#1f2937' }}>{gc.name}</span>
                        {(gc.company || gc.phone || gc.email) && (
                          <span style={{ fontSize:11, color:'#6b7280' }}>{[gc.company, gc.phone, gc.email].filter(Boolean).join(' · ')}</span>
                        )}
                      </button>
                    ))}
                  </div>
                </div>
              )}
            </div>
          )}

          {/* Row 1: שם + תפקיד */}
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
            <div>
              <label style={{ fontSize:11, fontWeight:700, color:'#6b7280', display:'block', marginBottom:4 }}>שם מלא *</label>
              <input value={form.name} onChange={e => f('name', e.target.value)}
                style={{ width:'100%', padding:'8px 10px', border:'1px solid #e5e7eb', borderRadius:7, fontSize:13, fontFamily:'inherit', boxSizing:'border-box', outline:'none' }}/>
            </div>
            <div>
              <label style={{ fontSize:11, fontWeight:700, color:'#6b7280', display:'block', marginBottom:4 }}>תפקיד *</label>
              <RoleInput value={form.role} onChange={v => f('role', v)}/>
            </div>
          </div>

          {/* Row 2: טלפון נייד + מייל אישי */}
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
            <div>
              <label style={{ fontSize:11, fontWeight:700, color:'#6b7280', display:'block', marginBottom:4 }}>טלפון נייד</label>
              <input value={form.phone} onChange={e => f('phone', e.target.value)} placeholder="05X-XXXXXXX" dir="ltr"
                style={{ width:'100%', padding:'8px 10px', border:'1px solid #e5e7eb', borderRadius:7, fontSize:13, fontFamily:'inherit', boxSizing:'border-box', outline:'none', textAlign:'right' }}/>
            </div>
            <div>
              <label style={{ fontSize:11, fontWeight:700, color:'#6b7280', display:'block', marginBottom:4 }}>מייל אישי</label>
              <input value={form.email} onChange={e => f('email', e.target.value)} placeholder="name@company.co.il" dir="ltr"
                style={{ width:'100%', padding:'8px 10px', border:'1px solid #e5e7eb', borderRadius:7, fontSize:13, fontFamily:'inherit', boxSizing:'border-box', outline:'none', textAlign:'right' }}/>
            </div>
          </div>

          {/* Row 3: טלפון משרד + מייל משרד */}
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
            <div>
              <label style={{ fontSize:11, fontWeight:700, color:'#6b7280', display:'block', marginBottom:4 }}>טלפון משרד</label>
              <input value={form.office_phone||''} onChange={e => f('office_phone', e.target.value)} placeholder="03-XXXXXXX" dir="ltr"
                style={{ width:'100%', padding:'8px 10px', border:'1px solid #e5e7eb', borderRadius:7, fontSize:13, fontFamily:'inherit', boxSizing:'border-box', outline:'none', textAlign:'right' }}/>
            </div>
            <div>
              <label style={{ fontSize:11, fontWeight:700, color:'#6b7280', display:'block', marginBottom:4 }}>מייל משרד</label>
              <input value={form.office_email||''} onChange={e => f('office_email', e.target.value)} placeholder="info@company.co.il" dir="ltr"
                style={{ width:'100%', padding:'8px 10px', border:'1px solid #e5e7eb', borderRadius:7, fontSize:13, fontFamily:'inherit', boxSizing:'border-box', outline:'none', textAlign:'right' }}/>
            </div>
          </div>

          {/* חברה / ארגון */}
          <div>
            <label style={{ fontSize:11, fontWeight:700, color:'#6b7280', display:'block', marginBottom:4 }}>חברה / ארגון</label>
            <input value={form.company} onChange={e => f('company', e.target.value)}
              style={{ width:'100%', padding:'8px 10px', border:'1px solid #e5e7eb', borderRadius:7, fontSize:13, fontFamily:'inherit', boxSizing:'border-box', outline:'none' }}/>
          </div>

          {/* שיוך */}
          <div>
            <label style={{ fontSize:11, fontWeight:700, color:'#6b7280', display:'block', marginBottom:6 }}>שיוך</label>

            {/* הודעת auto-scope ליזם */}
            {['יזם','שותף יזם'].includes(form.role) && (
              <div style={{ fontSize:11, color:'#7c3aed', background:'#fdf4ff', border:'1px solid #e9d5ff', borderRadius:6, padding:'5px 10px', marginBottom:8 }}>
                ✦ תפקיד יזם — שויך אוטומטית ל-CRM (לקוחות)
              </div>
            )}

            <div style={{ display:'flex', gap:6, flexWrap:'wrap' }}>
              {[
                { k:'library',  label:'📚 ספרייה כללית' },
                { k:'client',   label:'🏢 לקוח ספציפי'  },
                { k:'location', label:'📍 לוקיישן'       },
              ].map(opt => (
                <button key={opt.k} onClick={() => { f('scope', opt.k); f('scope_id', null); if (opt.k !== 'client') f('scope_ids', []); }}
                  style={{ padding:'7px 14px', borderRadius:8, border:'2px solid', fontSize:12, fontWeight:700, cursor:'pointer', fontFamily:'inherit', transition:'all .15s',
                    borderColor: form.scope === opt.k ? '#1a2c4a' : '#e5e7eb',
                    background:  form.scope === opt.k ? '#1a2c4a' : '#f9fafb',
                    color:       form.scope === opt.k ? '#fff'    : '#374151',
                  }}>
                  {opt.label}
                </button>
              ))}
            </div>

            {/* בחירת לקוח + הוספה ידנית */}
            {form.scope === 'client' && (
              <div style={{ marginTop:10 }}>
                <div style={{ display:'flex', flexWrap:'wrap', gap:6 }}>
                  {allClients.map(cl => {
                    const selectedIds = form.scope_ids || [];
                    const isSelected = selectedIds.includes(cl.id);
                    const toggleClient = () => {
                      const newIds = isSelected
                        ? selectedIds.filter(i => i !== cl.id)
                        : [...selectedIds, cl.id];
                      f('scope_ids', newIds);
                      f('scope_id', newIds[0] || null); // primary = first
                    };
                    return (
                    <button key={cl.id} onClick={toggleClient}
                      style={{ padding:'5px 12px', borderRadius:20, border:'1px solid', fontSize:12, cursor:'pointer', fontFamily:'inherit',
                        borderColor: isSelected ? '#1d4ed8' : '#e5e7eb',
                        background:  isSelected ? '#eff6ff' : '#f9fafb',
                        color:       isSelected ? '#1d4ed8' : '#374151',
                        fontWeight:  isSelected ? 700 : 400,
                      }}>
                      {isSelected ? '✓ ' : ''}{cl.emoji} {cl.name}
                    </button>
                    );
                  })}
                </div>
                <div style={{ display:'flex', gap:6, marginTop:8 }}>
                  <input value={newClientInput} onChange={e => setNewClientInput(e.target.value)}
                    onKeyDown={e => e.key === 'Enter' && addCustomClient()}
                    placeholder="+ הוסף לקוח חדש..."
                    style={{ flex:1, padding:'6px 10px', border:'1px dashed #93c5fd', borderRadius:7, fontSize:12, fontFamily:'inherit', outline:'none', direction:'rtl', background:'#f0f9ff' }}/>
                  <button onClick={addCustomClient} disabled={!newClientInput.trim()}
                    style={{ padding:'6px 12px', background: newClientInput.trim() ? '#1d4ed8' : '#d1d5db', color:'#fff', border:'none', borderRadius:7, fontSize:12, cursor: newClientInput.trim() ? 'pointer' : 'default', fontFamily:'inherit', fontWeight:700 }}>
                    הוסף
                  </button>
                </div>
              </div>
            )}

            {/* בחירת לוקיישן + הוספה ידנית */}
            {form.scope === 'location' && (
              <div style={{ marginTop:10 }}>
                <div style={{ display:'flex', flexWrap:'wrap', gap:6 }}>
                  {allLocations.map(loc => (
                    <button key={loc.id} onClick={() => f('scope_id', loc.id)}
                      style={{ padding:'5px 12px', borderRadius:20, border:'1px solid', fontSize:12, cursor:'pointer', fontFamily:'inherit',
                        borderColor: form.scope_id === loc.id ? '#059669' : '#e5e7eb',
                        background:  form.scope_id === loc.id ? '#d1fae5' : '#f9fafb',
                        color:       form.scope_id === loc.id ? '#059669' : '#374151',
                        fontWeight:  form.scope_id === loc.id ? 700 : 400,
                      }}>
                      {loc.emoji} {loc.name}
                    </button>
                  ))}
                </div>
                <div style={{ display:'flex', gap:6, marginTop:8 }}>
                  <input value={newLocationInput} onChange={e => setNewLocationInput(e.target.value)}
                    onKeyDown={e => e.key === 'Enter' && addCustomLocation()}
                    placeholder="+ הוסף לוקיישן חדש..."
                    style={{ flex:1, padding:'6px 10px', border:'1px dashed #86efac', borderRadius:7, fontSize:12, fontFamily:'inherit', outline:'none', direction:'rtl', background:'#f0fdf4' }}/>
                  <button onClick={addCustomLocation} disabled={!newLocationInput.trim()}
                    style={{ padding:'6px 12px', background: newLocationInput.trim() ? '#059669' : '#d1d5db', color:'#fff', border:'none', borderRadius:7, fontSize:12, cursor: newLocationInput.trim() ? 'pointer' : 'default', fontFamily:'inherit', fontWeight:700 }}>
                    הוסף
                  </button>
                </div>
              </div>
            )}
          </div>

          {/* הערות */}
          <div>
            <label style={{ fontSize:11, fontWeight:700, color:'#6b7280', display:'block', marginBottom:4 }}>הערות</label>
            <textarea value={form.notes} onChange={e => f('notes', e.target.value)} rows={2}
              placeholder="הערות חופשיות..."
              style={{ width:'100%', padding:'8px 10px', border:'1px solid #e5e7eb', borderRadius:7, fontSize:13, fontFamily:'inherit', boxSizing:'border-box', outline:'none', resize:'none' }}/>
          </div>

          {/* מועדף */}
          <label style={{ display:'flex', alignItems:'center', gap:10, cursor:'pointer' }}>
            <input type="checkbox" checked={form.is_favorite} onChange={e => f('is_favorite', e.target.checked)}
              style={{ width:16, height:16, cursor:'pointer' }}/>
            <span style={{ fontSize:13, color:'#374151' }}>⭐ הוסף למועדפים</span>
          </label>
        </div>

        {/* Footer */}
        <div style={{ padding:'12px 18px', borderTop:'1px solid #f3f4f6', display:'flex', gap:8, justifyContent:'flex-end' }}>
          <button onClick={onClose}
            style={{ padding:'9px 20px', borderRadius:7, border:'1px solid #e5e7eb', background:'#fff', fontSize:13, cursor:'pointer', fontFamily:'inherit' }}>
            ביטול
          </button>
          <button onClick={() => {
            try {
              const name = (form.name || '').trim();
              if (!name) return alert('שם חובה');
              onSave({
                ...form,
                name,
                scope_ids: Array.isArray(form.scope_ids) ? form.scope_ids : [],
                id: form.id || ('c_' + Date.now()),
              });
            } catch (err) {
              alert('שגיאה: ' + (err?.message || String(err)));
            }
          }} style={{ padding:'9px 24px', borderRadius:7, border:'none', background:'#1a2c4a', color:'#fff', fontSize:13, fontWeight:700, cursor:'pointer', fontFamily:'inherit' }}>
            {isEdit ? 'שמור שינויים' : 'הוסף איש קשר'}
          </button>
        </div>
      </div>
    </div>
  );
};

// ── Search bar ────────────────────────────────────────────────────────────────
const SearchBar = ({ value, onChange, placeholder }) => (
  <div style={{ background:'#fff', borderRadius:9, border:'1px solid #e5e7eb', padding:'8px 12px', display:'flex', alignItems:'center', gap:8 }}>
    <span style={{ color:'#9ca3af', fontSize:15 }}>🔍</span>
    <input value={value} onChange={e => onChange(e.target.value)}
      placeholder={placeholder || 'חפש...'}
      style={{ flex:1, border:'none', background:'transparent', fontSize:13, fontFamily:'inherit', outline:'none', direction:'rtl' }}/>
    {value && <button onClick={() => onChange('')} style={{ background:'none', border:'none', cursor:'pointer', color:'#9ca3af', fontSize:15, padding:0, lineHeight:1 }}>✕</button>}
  </div>
);

// ── Empty state ───────────────────────────────────────────────────────────────
const EmptyState = ({ icon, title, subtitle, action, onAction }) => (
  <div style={{ textAlign:'center', padding:'50px 20px' }}>
    <div style={{ fontSize:44, marginBottom:12 }}>{icon}</div>
    <div style={{ fontSize:15, fontWeight:700, color:'#374151', marginBottom:6 }}>{title}</div>
    {subtitle && <div style={{ fontSize:13, color:'#9ca3af', marginBottom:20 }}>{subtitle}</div>}
    {action && <button onClick={onAction} style={{ padding:'9px 22px', borderRadius:7, border:'none', background:'#1a2c4a', color:'#fff', fontSize:13, fontWeight:700, cursor:'pointer', fontFamily:'inherit' }}>{action}</button>}
  </div>
);

// ── Tab: ספרייה ───────────────────────────────────────────────────────────────
const LibraryTab = ({ contacts, onEdit, onDelete, onToggleFavorite, onAdd, onOpen }) => {
  const [search, setSearch] = useState('');
  const [roleFilter, setRoleFilter] = useState('');

  const filtered = useMemo(() => {
    const lib = contacts.filter(c => c.scope === 'library');
    return lib.filter(c => {
      const q = search.toLowerCase();
      const matchSearch = !q || c.name.toLowerCase().includes(q) || c.company?.toLowerCase().includes(q) || c.role?.toLowerCase().includes(q);
      const matchRole = !roleFilter || c.role === roleFilter;
      return matchSearch && matchRole;
    });
  }, [contacts, search, roleFilter]);

  const roles = useMemo(() => [...new Set(contacts.filter(c=>c.scope==='library').map(c=>c.role).filter(Boolean))], [contacts]);

  return (
    <div>
      {/* Filters */}
      <div style={{ display:'flex', flexDirection:'column', gap:8, marginBottom:14 }}>
        <SearchBar value={search} onChange={setSearch} placeholder="חפש בספרייה..."/>
        {roles.length > 0 && (
          <select
            value={roleFilter}
            onChange={e => setRoleFilter(e.target.value)}
            style={{ width:'100%', padding:'8px 12px', border:'1px solid #e5e7eb', borderRadius:9, fontSize:13, fontFamily:'Assistant,sans-serif', background:'#fff', color:'#1f2937', outline:'none', direction:'rtl' }}>
            <option value=''>כל התפקידים ({contacts.filter(c=>c.scope==='library').length})</option>
            {roles.map(r => <option key={r} value={r}>{r}</option>)}
          </select>
        )}
      </div>

      {filtered.length === 0 && (
        <EmptyState icon="📚" title="הספרייה ריקה" subtitle="הוסף אנשי קשר לספרייה הכללית" action="+ הוסף ראשון" onAction={onAdd}/>
      )}

      <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
        {filtered.map(c => (
          <ContactCard key={c.id} contact={c} onEdit={onEdit} onDelete={onDelete} onToggleFavorite={onToggleFavorite} onOpen={onOpen}/>
        ))}
      </div>
    </div>
  );
};

// ── Tab: לקוחות ───────────────────────────────────────────────────────────────
const ClientsTab = ({ contacts, onEdit, onDelete, onToggleFavorite, onAdd, onOpen }) => {
  const [search, setSearch] = useState('');
  const [openClients, setOpenClients] = useState({});
  const allCollapsed = useMemo(() => Object.values(openClients).some(v => v === false), [openClients]);
  const collapseAll = () => {
    const keys = Object.keys(filtered);
    const newState = {};
    if (allCollapsed) { keys.forEach(k => { newState[k] = true; }); }
    else              { keys.forEach(k => { newState[k] = false; }); }
    setOpenClients(newState);
  };

  const clientContacts = useMemo(() => contacts.filter(c => c.scope === 'client'), [contacts]);

  const allClientsForTab = useMemo(() => [...DEMO_CLIENTS, ...loadCustomClients()], [contacts]);

  const byClient = useMemo(() => {
    const map = {};
    allClientsForTab.forEach(cl => {
      const list = clientContacts.filter(c =>
        (c.scope_ids && c.scope_ids.includes(cl.id)) || c.scope_id === cl.id
      );
      if (list.length > 0) map[cl.id] = { client: cl, contacts: list };
    });
    // unassigned — no scope_ids AND no scope_id match
    const unassigned = clientContacts.filter(c => {
      const hasIds = c.scope_ids && c.scope_ids.length > 0;
      const hasScopeId = c.scope_id && allClientsForTab.find(cl => cl.id === c.scope_id);
      return !hasIds && !hasScopeId;
    });
    if (unassigned.length > 0) map['__unassigned'] = { client: { id:'__unassigned', name:'לא משויך', emoji:'❓' }, contacts: unassigned };
    return map;
  }, [clientContacts, allClientsForTab]);

  const filtered = useMemo(() => {
    if (!search.trim()) return byClient;
    const q = search.toLowerCase();
    const result = {};
    Object.entries(byClient).forEach(([k, v]) => {
      const fc = v.contacts.filter(c => c.name.toLowerCase().includes(q) || c.company?.toLowerCase().includes(q) || c.role?.toLowerCase().includes(q));
      if (fc.length > 0) result[k] = { ...v, contacts: fc };
    });
    return result;
  }, [byClient, search]);

  const toggle = (k) => setOpenClients(p => ({ ...p, [k]: !p[k] }));

  if (clientContacts.length === 0) return (
    <EmptyState icon="🏢" title="אין אנשי קשר לקוחות" subtitle="הוסף אנשי קשר ושייך אותם ללקוח" action="+ הוסף" onAction={onAdd}/>
  );

  return (
    <div>
      <div style={{ display:'flex', gap:8, alignItems:'center' }}>
        <SearchBar value={search} onChange={setSearch} placeholder="חפש לפי שם, חברה, תפקיד..." />
        <button onClick={collapseAll}
          style={{ flexShrink:0, padding:'6px 12px', borderRadius:8, border:'1px solid #e5e7eb', background:'#f9fafb', fontSize:12, fontWeight:600, cursor:'pointer', fontFamily:'inherit', whiteSpace:'nowrap', color:'#374151' }}>
          {allCollapsed ? '⊞ פתח הכל' : '⊟ כווץ הכל'}
        </button>
      </div>
      <div style={{ display:'flex', flexDirection:'column', gap:10, marginTop:12 }}>
        {Object.entries(filtered).map(([k, { client, contacts: list }]) => {
          const isOpen = openClients[k] !== false; // default open
          return (
            <div key={k} style={{ background:'#fff', border:'1px solid #e5e7eb', borderRadius:12, overflow:'hidden' }}>
              <button onClick={() => toggle(k)} style={{
                width:'100%', padding:'12px 14px', background:'transparent', border:'none', cursor:'pointer',
                display:'flex', alignItems:'center', gap:10, fontFamily:'inherit',
              }}>
                <span style={{ fontSize:20 }}>{client.emoji}</span>
                <span style={{ flex:1, fontSize:14, fontWeight:700, color:'#1f2937', textAlign:'right' }}>{client.name}</span>
                <span style={{ fontSize:11, background:'#f3f4f6', color:'#6b7280', padding:'2px 8px', borderRadius:10, fontWeight:600 }}>{list.length}</span>
                <span style={{ color:'#9ca3af', fontSize:12 }}>{isOpen ? '▲' : '▼'}</span>
              </button>
              {isOpen && (
                <div style={{ padding:'0 12px 12px', display:'flex', flexDirection:'column', gap:6, borderTop:'1px solid #f3f4f6' }}>
                  {list.map(c => (
                    <ContactCard key={c.id} contact={c} onEdit={onEdit} onDelete={onDelete} onToggleFavorite={onToggleFavorite} onOpen={onOpen}/>
                  ))}
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
};

// ── Tab: לוקיישנים ────────────────────────────────────────────────────────────
const LocationsTab = ({ contacts, onEdit, onDelete, onToggleFavorite, onAdd, onOpen }) => {
  const [search, setSearch] = useState('');
  const [openLocs, setOpenLocs] = useState({});

  const locContacts = useMemo(() => contacts.filter(c => c.scope === 'location'), [contacts]);

  const allLocsForTab = useMemo(() => [...DEMO_LOCATIONS, ...loadCustomLocs()], [contacts]);

  const byLoc = useMemo(() => {
    const map = {};
    allLocsForTab.forEach(loc => {
      const list = locContacts.filter(c => c.scope_id === loc.id);
      if (list.length > 0) map[loc.id] = { loc, contacts: list };
    });
    // unassigned locations
    const unassigned = locContacts.filter(c => !allLocsForTab.find(loc => loc.id === c.scope_id));
    if (unassigned.length > 0) map['__unassigned'] = { loc: { id:'__unassigned', name:'לא משויך', emoji:'❓', city:'' }, contacts: unassigned };
    return map;
  }, [locContacts, allLocsForTab]);

  const filtered = useMemo(() => {
    if (!search.trim()) return byLoc;
    const q = search.toLowerCase();
    const result = {};
    Object.entries(byLoc).forEach(([k, v]) => {
      const fc = v.contacts.filter(c => c.name.toLowerCase().includes(q) || c.company?.toLowerCase().includes(q));
      if (fc.length > 0) result[k] = { ...v, contacts: fc };
    });
    return result;
  }, [byLoc, search]);

  const toggle = (k) => setOpenLocs(p => ({ ...p, [k]: !p[k] }));

  if (locContacts.length === 0) return (
    <EmptyState icon="📍" title="אין אנשי קשר לוקיישנים" subtitle="הוסף אנשי קשר ושייך אותם ללוקיישן" action="+ הוסף" onAction={onAdd}/>
  );

  return (
    <div>
      <SearchBar value={search} onChange={setSearch} placeholder="חפש לפי שם, חברה..." />
      <div style={{ display:'flex', flexDirection:'column', gap:10, marginTop:12 }}>
        {Object.entries(filtered).map(([k, { loc, contacts: list }]) => {
          const isOpen = openLocs[k] !== false;
          return (
            <div key={k} style={{ background:'#fff', border:'1px solid #e5e7eb', borderRadius:12, overflow:'hidden' }}>
              <button onClick={() => toggle(k)} style={{
                width:'100%', padding:'12px 14px', background:'transparent', border:'none', cursor:'pointer',
                display:'flex', alignItems:'center', gap:10, fontFamily:'inherit',
              }}>
                <span style={{ fontSize:20 }}>{loc.emoji}</span>
                <div style={{ flex:1, textAlign:'right' }}>
                  <div style={{ fontSize:14, fontWeight:700, color:'#1f2937' }}>{loc.name}</div>
                  <div style={{ fontSize:11, color:'#9ca3af' }}>{loc.city}</div>
                </div>
                <span style={{ fontSize:11, background:'#f3f4f6', color:'#6b7280', padding:'2px 8px', borderRadius:10, fontWeight:600 }}>{list.length}</span>
                <span style={{ color:'#9ca3af', fontSize:12 }}>{isOpen ? '▲' : '▼'}</span>
              </button>
              {isOpen && (
                <div style={{ padding:'0 12px 12px', display:'flex', flexDirection:'column', gap:6, borderTop:'1px solid #f3f4f6' }}>
                  {list.map(c => (
                    <ContactCard key={c.id} contact={c} onEdit={onEdit} onDelete={onDelete} onToggleFavorite={onToggleFavorite} onOpen={onOpen}/>
                  ))}
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
};

// ── Tab: מועדפים ──────────────────────────────────────────────────────────────
const FavoritesTab = ({ contacts, onEdit, onDelete, onToggleFavorite, onOpen }) => {
  const [search, setSearch] = useState('');
  const favs = useMemo(() => {
    const f = contacts.filter(c => c.is_favorite);
    if (!search.trim()) return f;
    const q = search.toLowerCase();
    return f.filter(c => c.name.toLowerCase().includes(q) || c.company?.toLowerCase().includes(q));
  }, [contacts, search]);

  if (!contacts.filter(c=>c.is_favorite).length) return (
    <EmptyState icon="⭐" title="אין מועדפים" subtitle={`לחץ ☆ על איש קשר כדי להוסיף למועדפים`}/>
  );

  return (
    <div>
      <SearchBar value={search} onChange={setSearch} placeholder="חפש במועדפים..."/>
      <div style={{ marginTop:2, marginBottom:12 }}>
        <div style={{ fontSize:12, color:'#9ca3af', padding:'8px 0' }}>
          {favs.length} מועדפים — מופיעים כהצעות חכמות בכל פרויקט
        </div>
      </div>
      {favs.length === 0 && (
        <div style={{ textAlign:'center', padding:'20px', color:'#9ca3af', fontSize:13 }}>לא נמצאו תוצאות</div>
      )}
      <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
        {favs.map(c => (
          <ContactCard key={c.id} contact={c} onEdit={onEdit} onDelete={onDelete} onToggleFavorite={onToggleFavorite} onOpen={onOpen}/>
        ))}
      </div>
    </div>
  );
};

// ── Main Screen ───────────────────────────────────────────────────────────────
const ContactsScreen = ({ onBack, onOpenContact, initialTab = 'library' }) => {
  const [contacts, setContacts] = useState(loadContacts); // טעינה ראשונית מ-cache מקומי לציור מהיר
  const [tab, setTab] = useState(initialTab);
  const [modal, setModal] = useState(null); // null | {mode:'add'|'edit', contact?}
  const [syncStatus, setSyncStatus] = useState(null); // null | 'loading' | 'done' | 'error'
  const [busy, setBusy] = useState(false);

  const refresh = async () => {
    if (!window.ContactsStore) return;
    const all = await window.ContactsStore.listAll();
    setContacts(all);
  };

  // טעינה מ-Supabase ב-mount (אחרי migration אוטומטי אם רלוונטי)
  useEffect(() => {
    if (!window.ContactsStore) return;
    setSyncStatus('loading');
    (async () => {
      try {
        await window.ContactsStore.migrateLocalStorageIfNeeded();
        await refresh();
        setSyncStatus('done');
        setTimeout(() => setSyncStatus(null), 2000);
      } catch (e) {
        console.warn('[ContactsScreen] load failed:', e.message);
        setSyncStatus('error');
      }
    })();
  }, []);

  const saveContact = async (c) => {
    if (!window.ContactsStore) { alert('Supabase לא זמין'); return; }
    setBusy(true);
    try {
      const isNew = !c.id || !contacts.find(x => x.id === c.id);
      if (isNew) await window.ContactsStore.create(c);
      else       await window.ContactsStore.update(c.id, c);
      await refresh();
      setModal(null);
    } catch (e) {
      alert('שגיאה בשמירה: ' + (e.message || 'unknown'));
    } finally { setBusy(false); }
  };

  const deleteContact = async (id) => {
    if (!confirm('למחוק איש קשר זה?')) return;
    if (!window.ContactsStore) return;
    setBusy(true);
    try {
      await window.ContactsStore.remove(id);
      await refresh();
    } catch (e) {
      alert('שגיאה במחיקה: ' + (e.message || 'unknown'));
    } finally { setBusy(false); }
  };

  const toggleFavorite = async (id) => {
    const c = contacts.find(x => x.id === id);
    if (!c || !window.ContactsStore) return;
    try {
      await window.ContactsStore.update(id, { ...c, is_favorite: !c.is_favorite });
      await refresh();
    } catch (e) {
      console.warn('[ContactsScreen] toggleFavorite failed:', e.message);
    }
  };

  // ── Admin: Excel export ────────────────────────────────────────────────
  const handleExportExcel = () => {
    if (!window.ContactsStore) return;
    const date = new Date().toISOString().slice(0,10);
    window.ContactsStore.exportToExcel(contacts, `YBP_אנשי_קשר_${date}.xlsx`);
  };

  const openAdd = () => setModal({ mode:'add' });
  const openEdit = (contact) => setModal({ mode:'edit', contact });

  const tabs = [
    { k:'library',   label:'📚 ספרייה', count: contacts.filter(c=>c.scope==='library').length },
    { k:'clients',   label:'🏢 לקוחות', count: contacts.filter(c=>c.scope==='client').length },
    { k:'locations', label:'📍 לוקיישנים', count: contacts.filter(c=>c.scope==='location').length },
    { k:'favorites', label:'⭐ מועדפים', count: contacts.filter(c=>c.is_favorite).length },
  ];

  const sharedTabProps = { contacts, onEdit: openEdit, onDelete: deleteContact, onToggleFavorite: toggleFavorite, onAdd: openAdd, onOpen: (c) => onOpenContact?.(c.id) };

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

      {/* Header */}
      <header style={{ background:'#1a2c4a', color:'#fff', padding:'14px 16px 0', position:'sticky', top:0, zIndex:10 }}>
        <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:12 }}>
          {onBack && (
            <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, fontSize:16 }}>
              ›
            </button>
          )}
          <div style={{ flex:1 }}>
            <div style={{ fontSize:11, opacity:0.6, marginBottom:1 }}>YBPROJECTS</div>
            <div style={{ fontSize:17, fontWeight:800, letterSpacing:-0.3 }}>👥 מאגר אנשי קשר</div>
          </div>
          <div style={{ display:'flex', gap:6, alignItems:'center', flexWrap:'wrap' }}>
            <button onClick={handleExportExcel} disabled={busy || contacts.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?'not-allowed':'pointer', fontFamily:'inherit', opacity: busy?0.5:1,
            }}>📥 Excel</button>
            <button onClick={openAdd} 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,
            }}>
              + הוסף
            </button>
          </div>
        </div>

        {/* Stats strip */}
        <div style={{ display:'flex', gap:14, marginBottom:10, opacity:0.75, alignItems:'center' }}>
          <span style={{ fontSize:11 }}>{contacts.length} אנשי קשר</span>
          <span style={{ fontSize:11 }}>· {contacts.filter(c=>c.is_favorite).length} מועדפים</span>
          <span style={{ fontSize:11 }}>· {contacts.filter(c=>c.scope==='client').length} לקוחות</span>
          {syncStatus === 'loading' && <span style={{ fontSize:10, opacity:0.8 }}>⟳ טוען מ-Supabase...</span>}
          {syncStatus === 'done'    && <span style={{ fontSize:10, color:'#86efac' }}>✓ סונכרן</span>}
          {syncStatus === 'error'   && <span style={{ fontSize:10, color:'#fca5a5' }}>⚠ שגיאת סנכרון</span>}
        </div>

        {/* Tabs */}
        <div style={{ display:'flex', borderTop:'1px solid rgba(255,255,255,0.1)', marginRight:-16, marginLeft:-16 }}>
          {tabs.map(t => (
            <button key={t.k} onClick={() => setTab(t.k)} style={{
              flex:1, padding:'10px 4px 8px', background:'transparent', border:'none', cursor:'pointer',
              borderBottom: tab === t.k ? '2px solid #b5a882' : '2px solid transparent',
              color: tab === t.k ? '#fff' : 'rgba(255,255,255,0.5)',
              fontFamily:'inherit', fontSize:11, fontWeight: tab === t.k ? 700 : 400,
              display:'flex', flexDirection:'column', alignItems:'center', gap:2, transition:'all .15s',
            }}>
              <span>{t.label}</span>
              {t.count > 0 && <span style={{ fontSize:10, background: tab===t.k ? '#b5a882' : 'rgba(255,255,255,0.15)', color: tab===t.k ? '#1a2c4a' : '#fff', padding:'0px 6px', borderRadius:8, fontWeight:700 }}>{t.count}</span>}
            </button>
          ))}
        </div>
      </header>

      {/* Content */}
      <div style={{ flex:1, maxWidth:640, width:'100%', margin:'0 auto', padding:'16px', boxSizing:'border-box' }}>
        {tab === 'library'   && <LibraryTab   {...sharedTabProps}/>}
        {tab === 'clients'   && <ClientsTab   {...sharedTabProps}/>}
        {tab === 'locations' && <LocationsTab {...sharedTabProps}/>}
        {tab === 'favorites' && <FavoritesTab {...sharedTabProps}/>}
      </div>

      {/* Footer */}
      <div style={{ textAlign:'center', padding:'12px', fontSize:11, color:'#9ca3af', borderTop:'1px solid #e5e7eb', background:'#fff' }}>
        © 2026 YBPROJECTS · כל הזכויות שמורות
      </div>

      {/* Add / Edit modal */}
      {modal && (
        <ContactModal
          contact={modal.mode === 'edit' ? modal.contact : null}
          onSave={saveContact}
          onClose={() => setModal(null)}
          allContactsList={contacts}
        />
      )}
    </div>
  );
};

window.ContactsScreen = ContactsScreen;
})();
