// ContactDetailScreen — s-contact-detail
(function(){
const { useState, useEffect, useMemo } = React;

// ── Shared constants ──────────────────────────────────────────────────────────
const STORAGE_KEY = 'ybp_contacts_v1';
const PROJ_CONTACTS_KEY = 'ybp_proj_contacts_v2';

const DEMO_CLIENTS = [
  { id:'client_roladin',    name:'רולדין',      emoji:'🥐' },
  { id:'client_pizza',      name:'פיצה האט',    emoji:'🍕' },
  { id:'client_mcdonalds',  name:'מקדונלדס',    emoji:'🍔' },
  { id:'client_wework',     name:'WeWork',       emoji:'🏢' },
  { id:'client_superpharm', name:'סופר-פארם',   emoji:'💊' },
];
const DEMO_LOCATIONS = [
  { id:'loc_natbag',    name:'נתב"ג טרמינל 3', emoji:'✈️' },
  { id:'loc_ayalon',   name:'קניון איילון',     emoji:'🛍️' },
  { id:'loc_tel_aviv', name:'תל אביב מרכז',     emoji:'🏙️' },
  { id:'loc_haifa',    name:'קניון חיפה',        emoji:'🌊' },
  { id:'loc_beer',     name:'באר שבע גרנד',      emoji:'🏜️' },
];

const ROLE_GROUPS = [
  { group:'ניהול ויזמות',        roles:['יזם','שותף יזם','מנכ"ל','מנכ"לית','סמנכ"ל כספים','סמנכ"לית שיווק','הנהל"ח','מנהל בינוי','מנהל שיווק','מנהל אחזקה','מנהל פרויקטים','ניהול פרויקט','משכיר'] },
  { group:'אדריכלות ותכנון',     roles:['אדריכל','אדריכלים','מודד','קונסטרוקטור','תכנון ורישוי עסקים'] },
  { group:'יועצים',              roles:['יועצי בטיחות','יועצי נגישות','יועצי רישוי','יועצי חשמל','יועצי תאורה','יועצי מיזוג אוויר','יועצי אינסטלציה','יועצי סאונד','יועצי אקוסטיקה','יועצי מטבחים','יועצי איטום','יועצי תנועה'] },
  { group:'קבלני ביצוע',         roles:['קבלני גמר','קבלני מיזוג אוויר','קבלני חשמל','קבלני אינסטלציה','קבלן בינוי'] },
  { group:'מערכות ומתח נמוך',   roles:['תקשורת/מצלמות/מתח נמוך','מצלמות','סאונד','מערכות גילוי אש','מערכות כיבוי אש'] },
  { group:'ציוד ומטבח',          roles:['ציוד קירור ומקררים','ציוד מטבח','נירוסטה'] },
  { group:'עבודות גמר וריהוט',  roles:['נגרות','מסגרות','במות רמה','תאורה','תאורה ובקרה','שילוט','ריהוט','מידוף'] },
  { group:'אחר',                 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' };
};

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

const loadContacts = () => {
  try { return JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]'); } catch { return []; }
};
const saveContacts = (contacts) => {
  try { localStorage.setItem(STORAGE_KEY, JSON.stringify(contacts)); } catch {}
};

// Which projects have this contact assigned? (fallback ל-localStorage cache)
const getAssignedProjectsCache = (contactId) => {
  try {
    const all = JSON.parse(localStorage.getItem(PROJ_CONTACTS_KEY) || '{}');
    return Object.entries(all)
      .filter(([, ids]) => ids.includes(contactId))
      .map(([projId]) => projId);
  } catch { return []; }
};

// async — שואב מ-project_contacts ב-Supabase, fallback ל-cache
async function fetchAssignedProjects(contactId) {
  try {
    if (window.YBP_SUPABASE) {
      const sb = await window.YBP_SUPABASE.getClient();
      const { data, error } = await sb.from('project_contacts').select('project_id').eq('contact_id', contactId);
      if (!error && data) return data.map(r => r.project_id);
    }
  } catch (e) { console.warn('[contact-detail] fetchAssignedProjects:', e.message); }
  return getAssignedProjectsCache(contactId);
}

// ── Edit modal (inline) ───────────────────────────────────────────────────────
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>
  );
};

// ── Info row ──────────────────────────────────────────────────────────────────
const InfoRow = ({ label, value, href, icon }) => {
  if (!value) return null;
  return (
    <div style={{ display:'flex', alignItems:'center', gap:12, padding:'12px 0', borderBottom:'1px solid #f3f4f6' }}>
      <div style={{ width:36, height:36, borderRadius:9, background:'#f3f4f6', display:'flex', alignItems:'center', justifyContent:'center', fontSize:16, flexShrink:0 }}>{icon}</div>
      <div style={{ flex:1 }}>
        <div style={{ fontSize:11, color:'#9ca3af', fontWeight:600, marginBottom:2 }}>{label}</div>
        {href
          ? <a href={href} style={{ fontSize:14, color:'#1a2c4a', fontWeight:600, textDecoration:'none', direction:'ltr', display:'block', textAlign:'right' }}>{value}</a>
          : <div style={{ fontSize:14, color:'#1f2937' }}>{value}</div>
        }
      </div>
    </div>
  );
};

// ── Activity item ─────────────────────────────────────────────────────────────
const ActivityItem = ({ icon, text, date, color }) => (
  <div style={{ display:'flex', gap:12, padding:'10px 0', borderBottom:'1px solid #f9fafb' }}>
    <div style={{ width:32, height:32, borderRadius:'50%', background: color || '#f3f4f6', display:'flex', alignItems:'center', justifyContent:'center', fontSize:14, flexShrink:0 }}>{icon}</div>
    <div style={{ flex:1 }}>
      <div style={{ fontSize:13, color:'#1f2937' }}>{text}</div>
      <div style={{ fontSize:11, color:'#9ca3af', marginTop:2 }}>{date}</div>
    </div>
  </div>
);

// ── Main ──────────────────────────────────────────────────────────────────────
const ContactDetailScreen = ({ contactId, onBack, onOpenProject }) => {
  const [contacts, setContacts] = useState(loadContacts); // initial paint מה-cache
  const [tab, setTab] = useState('info');
  const [editing, setEditing] = useState(false);
  const [form, setForm] = useState(null);
  const [newNote, setNewNote] = useState('');
  const [assignedProjIds, setAssignedProjIds] = useState(() => getAssignedProjectsCache(contactId));

  const contact = useMemo(() => contacts.find(c => c.id === contactId), [contacts, contactId]);

  useEffect(() => {
    if (contact) setForm({ ...contact });
  }, [contact]);

  // טעינה מ-Supabase ב-mount (אנשי קשר + פרויקטים משויכים)
  useEffect(() => {
    if (!window.ContactsStore) return;
    (async () => {
      try {
        const [all, projIds] = await Promise.all([
          window.ContactsStore.listAll(),
          fetchAssignedProjects(contactId),
        ]);
        setContacts(all);
        setAssignedProjIds(projIds);
      } catch (e) { console.warn('[contact-detail] load failed:', e.message); }
    })();
  }, [contactId]);

  const projects = useMemo(() => {
    const all = window.YBP_DATA?.projects || [];
    return assignedProjIds.map(id => all.find(p => p.id === id)).filter(Boolean);
  }, [assignedProjIds]);

  // Demo activity log
  const activity = useMemo(() => [
    { icon:'📋', text:`שויך לפרויקט ${projects[0]?.name || 'פרויקט'}`, date:'25 אפריל 2026', color:'#eff6ff' },
    { icon:'✉️', text:'נשלח אליו מייל — "עדכון תכנון שלב ב"', date:'22 אפריל 2026', color:'#f0fdf4' },
    { icon:'📞', text:'שיחת טלפון — 12 דקות', date:'18 אפריל 2026', color:'#fef3c7' },
    { icon:'📝', text:'נוסף למאגר אנשי קשר', date:'10 אפריל 2026', color:'#fdf4ff' },
  ], [projects]);

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

  const saveChanges = async () => {
    if (!window.ContactsStore) { alert('Supabase לא זמין'); return; }
    try {
      await window.ContactsStore.update(contactId, form);
      await refresh();
      setEditing(false);
    } catch (e) { alert('שגיאה בשמירה: ' + (e.message || 'unknown')); }
  };

  const toggleFavorite = async () => {
    if (!contact || !window.ContactsStore) return;
    try {
      await window.ContactsStore.update(contactId, { ...contact, is_favorite: !contact.is_favorite });
      await refresh();
    } catch (e) { console.warn('[contact-detail] toggleFavorite:', e.message); }
  };

  const addNote = async () => {
    if (!newNote.trim() || !contact || !window.ContactsStore) return;
    const timestamp = new Date().toLocaleDateString('he-IL');
    const updatedNotes = (contact.notes ? contact.notes + '\n' : '') + `[${timestamp}] ${newNote}`;
    try {
      await window.ContactsStore.update(contactId, { ...contact, notes: updatedNotes });
      await refresh();
      setNewNote('');
    } catch (e) { alert('שגיאה בהוספת הערה: ' + (e.message || 'unknown')); }
  };

  if (!contact) return (
    <div style={{ minHeight:'100vh', display:'flex', alignItems:'center', justifyContent:'center', fontFamily:'Assistant,sans-serif' }}>
      <div style={{ textAlign:'center' }}>
        <div style={{ fontSize:40, marginBottom:12 }}>😕</div>
        <div style={{ fontSize:15, color:'#374151' }}>איש קשר לא נמצא</div>
        <button onClick={onBack} style={{ marginTop:16, padding:'9px 22px', borderRadius:7, border:'none', background:'#1a2c4a', color:'#fff', fontSize:13, fontWeight:700, cursor:'pointer', fontFamily:'inherit' }}>חזרה</button>
      </div>
    </div>
  );

  const rc = ROLE_COLOR(contact.role);
  const scopeLabel = contact.scope === 'client'
    ? `🏢 ${DEMO_CLIENTS.find(c=>c.id===contact.scope_id)?.name || 'לקוח'}`
    : contact.scope === 'location'
    ? `📍 ${DEMO_LOCATIONS.find(l=>l.id===contact.scope_id)?.name || 'לוקיישן'}`
    : '📚 ספרייה כללית';

  const tabs = [
    { k:'info',     label:'פרטים' },
    { k:'projects', label:`פרויקטים (${projects.length})` },
    { k:'activity', label:'היסטוריה' },
    { k:'notes',    label:'הערות' },
  ];

  const f = (k, v) => setForm(p => ({ ...p, [k]: v }));

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

      {/* Header */}
      <div style={{ background:'#1a2c4a', padding:'14px 16px 0', position:'sticky', top:0, zIndex:10 }}>
        <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:16 }}>
          <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, color:'rgba(255,255,255,0.5)', marginBottom:1 }}>מאגר אנשי קשר</div>
            <div style={{ fontSize:16, fontWeight:800, color:'#fff' }}>פרטי איש קשר</div>
          </div>
          <button onClick={toggleFavorite} title={contact.is_favorite ? 'הסר ממועדפים' : 'הוסף למועדפים'}
            style={{ width:34, height:34, borderRadius:7, background:'rgba(255,255,255,0.1)', border:'1px solid rgba(255,255,255,0.2)', color: contact.is_favorite ? '#f59e0b' : 'rgba(255,255,255,0.5)', fontSize:18, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center' }}>
            {contact.is_favorite ? '★' : '☆'}
          </button>
          {!editing && (
            <button onClick={() => setEditing(true)}
              style={{ padding:'7px 14px', borderRadius:7, background:'#b5a882', color:'#1a2c4a', border:'none', fontSize:12, fontWeight:800, cursor:'pointer', fontFamily:'inherit' }}>
              ✏️ ערוך
            </button>
          )}
        </div>

        {/* Avatar + name */}
        <div style={{ display:'flex', alignItems:'center', gap:14, paddingBottom:16 }}>
          <div style={{ width:60, height:60, borderRadius:'50%', background: avatarColor(contact.name), color:'#fff', display:'flex', alignItems:'center', justifyContent:'center', fontSize:22, fontWeight:800, letterSpacing:-1, border:'3px solid rgba(255,255,255,0.2)', flexShrink:0 }}>
            {initials(contact.name)}
          </div>
          <div style={{ flex:1 }}>
            <div style={{ fontSize:20, fontWeight:800, color:'#fff', marginBottom:4 }}>{contact.name}</div>
            <div style={{ display:'flex', gap:6, flexWrap:'wrap' }}>
              <span style={{ fontSize:11, fontWeight:700, padding:'3px 9px', borderRadius:10, background:rc.bg, color:rc.color }}>{contact.role}</span>
              <span style={{ fontSize:11, padding:'3px 9px', borderRadius:10, background:'rgba(255,255,255,0.12)', color:'rgba(255,255,255,0.8)' }}>{scopeLabel}</span>
            </div>
          </div>
        </div>

        {/* Quick actions */}
        <div style={{ display:'flex', gap:8, marginBottom:14 }}>
          {contact.phone && (
            <a href={`tel:${contact.phone}`} style={{
              flex:1, padding:'9px', borderRadius:8, background:'rgba(255,255,255,0.1)', border:'1px solid rgba(255,255,255,0.15)',
              color:'#fff', textDecoration:'none', textAlign:'center', fontSize:12, fontWeight:700, display:'flex', alignItems:'center', justifyContent:'center', gap:5,
            }}>📞 התקשר</a>
          )}
          {contact.email && (
            <a href={`mailto:${contact.email}`} style={{
              flex:1, padding:'9px', borderRadius:8, background:'rgba(255,255,255,0.1)', border:'1px solid rgba(255,255,255,0.15)',
              color:'#fff', textDecoration:'none', textAlign:'center', fontSize:12, fontWeight:700, display:'flex', alignItems:'center', justifyContent:'center', gap:5,
            }}>✉️ מייל</a>
          )}
          {contact.phone && (
            <a href={`https://wa.me/972${contact.phone?.replace(/^0/,'').replace(/-/g,'')}`} target="_blank" rel="noreferrer" style={{
              flex:1, padding:'9px', borderRadius:8, background:'rgba(37,211,102,0.2)', border:'1px solid rgba(37,211,102,0.3)',
              color:'#fff', textDecoration:'none', textAlign:'center', fontSize:12, fontWeight:700, display:'flex', alignItems:'center', justifyContent:'center', gap:5,
            }}>💬 WhatsApp</a>
          )}
        </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,
              transition:'all .15s',
            }}>
              {t.label}
            </button>
          ))}
        </div>
      </div>

      {/* Content */}
      <div style={{ flex:1, maxWidth:640, width:'100%', margin:'0 auto', padding:16, boxSizing:'border-box' }}>

        {/* ── Tab: פרטים ─────────────────────────────────────────────────────── */}
        {tab === 'info' && !editing && (
          <div style={{ background:'#fff', borderRadius:12, padding:'4px 16px' }}>
            <InfoRow icon="📞" label="טלפון"   value={contact.phone} href={`tel:${contact.phone}`}/>
            <InfoRow icon="✉️" label="מייל"    value={contact.email} href={`mailto:${contact.email}`}/>
            <InfoRow icon="🏢" label="חברה"    value={contact.company}/>
            <InfoRow icon="💼" label="תפקיד"   value={contact.role}/>
            <InfoRow icon="🗂️" label="שיוך"    value={scopeLabel}/>
            {contact.notes && (
              <div style={{ padding:'12px 0' }}>
                <div style={{ fontSize:11, color:'#9ca3af', fontWeight:600, marginBottom:6 }}>הערות</div>
                <div style={{ fontSize:13, color:'#374151', whiteSpace:'pre-line', lineHeight:1.6 }}>{contact.notes}</div>
              </div>
            )}
          </div>
        )}

        {/* ── Tab: פרטים — edit mode ─────────────────────────────────────────── */}
        {tab === 'info' && editing && form && (
          <div style={{ background:'#fff', borderRadius:12, padding:16, display:'flex', flexDirection:'column', gap:14 }}>
            <div style={{ fontSize:13, fontWeight:700, color:'#1f2937', borderBottom:'1px solid #f3f4f6', paddingBottom:10 }}>עריכת פרטים</div>

            <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>

            <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)} 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)} 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>

            {/* Scope */}
            <div>
              <label style={{ fontSize:11, fontWeight:700, color:'#6b7280', display:'block', marginBottom:6 }}>שיוך</label>
              <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); }}
                    style={{ padding:'6px 14px', borderRadius:8, border:'2px solid', fontSize:12, fontWeight:700, cursor:'pointer', fontFamily:'inherit',
                      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:8, display:'flex', flexWrap:'wrap', gap:6 }}>
                  {DEMO_CLIENTS.map(cl => (
                    <button key={cl.id} onClick={() => f('scope_id', cl.id)}
                      style={{ padding:'4px 12px', borderRadius:16, border:'1px solid', fontSize:12, cursor:'pointer', fontFamily:'inherit',
                        borderColor: form.scope_id===cl.id ? '#1d4ed8' : '#e5e7eb',
                        background: form.scope_id===cl.id ? '#eff6ff' : '#f9fafb',
                        color: form.scope_id===cl.id ? '#1d4ed8' : '#374151', fontWeight: form.scope_id===cl.id ? 700 : 400,
                      }}>
                      {cl.emoji} {cl.name}
                    </button>
                  ))}
                </div>
              )}
              {form.scope === 'location' && (
                <div style={{ marginTop:8, display:'flex', flexWrap:'wrap', gap:6 }}>
                  {DEMO_LOCATIONS.map(loc => (
                    <button key={loc.id} onClick={() => f('scope_id', loc.id)}
                      style={{ padding:'4px 12px', borderRadius:16, 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>

            <div style={{ display:'flex', gap:8, justifyContent:'flex-end', paddingTop:4, borderTop:'1px solid #f3f4f6' }}>
              <button onClick={() => setEditing(false)} style={{ padding:'9px 20px', borderRadius:7, border:'1px solid #e5e7eb', background:'#fff', fontSize:13, cursor:'pointer', fontFamily:'inherit' }}>ביטול</button>
              <button onClick={saveChanges} style={{ padding:'9px 24px', borderRadius:7, border:'none', background:'#1a2c4a', color:'#fff', fontSize:13, fontWeight:700, cursor:'pointer', fontFamily:'inherit' }}>שמור</button>
            </div>
          </div>
        )}

        {/* ── Tab: פרויקטים ──────────────────────────────────────────────────── */}
        {tab === 'projects' && (
          <div>
            {projects.length === 0 ? (
              <div style={{ textAlign:'center', padding:'50px 20px', background:'#fff', borderRadius:12, border:'1px dashed #d1d5db' }}>
                <div style={{ fontSize:36, marginBottom:10 }}>📋</div>
                <div style={{ fontSize:14, fontWeight:600, color:'#374151', marginBottom:6 }}>לא משויך לפרויקטים</div>
                <div style={{ fontSize:12, color:'#9ca3af' }}>הוסף איש קשר זה לפרויקט מתוך מסך אנשי קשר של הפרויקט</div>
              </div>
            ) : (
              <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
                {projects.map(proj => (
                  <div key={proj.id} style={{ background:'#fff', border:'1px solid #e5e7eb', borderRadius:12, padding:'14px 16px', display:'flex', alignItems:'center', gap:12, cursor:'pointer', transition:'box-shadow .15s' }}
                    onClick={() => onOpenProject?.(proj.id)}
                    onMouseEnter={e => e.currentTarget.style.boxShadow='0 2px 8px rgba(0,0,0,0.08)'}
                    onMouseLeave={e => e.currentTarget.style.boxShadow='none'}>
                    <div style={{ width:42, height:42, borderRadius:9, background:'#1a2c4a', color:'#b5a882', display:'flex', alignItems:'center', justifyContent:'center', fontSize:18, flexShrink:0 }}>🏗️</div>
                    <div style={{ flex:1 }}>
                      <div style={{ fontSize:14, fontWeight:700, color:'#1f2937' }}>{proj.name}</div>
                      <div style={{ fontSize:12, color:'#6b7280', marginTop:2 }}>{proj.client} · {proj.status || 'פעיל'}</div>
                    </div>
                    <span style={{ fontSize:18, color:'#d1d5db' }}>‹</span>
                  </div>
                ))}
              </div>
            )}
          </div>
        )}

        {/* ── Tab: היסטוריה ──────────────────────────────────────────────────── */}
        {tab === 'activity' && (
          <div style={{ background:'#fff', borderRadius:12, padding:'4px 16px' }}>
            {activity.map((a, i) => (
              <ActivityItem key={i} {...a}/>
            ))}
          </div>
        )}

        {/* ── Tab: הערות ─────────────────────────────────────────────────────── */}
        {tab === 'notes' && (
          <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
            {/* Add note */}
            <div style={{ background:'#fff', borderRadius:12, padding:14 }}>
              <div style={{ fontSize:12, fontWeight:700, color:'#6b7280', marginBottom:8 }}>הוסף הערה</div>
              <textarea value={newNote} onChange={e => setNewNote(e.target.value)} rows={3}
                placeholder="כתוב הערה..."
                style={{ width:'100%', padding:'10px', border:'1px solid #e5e7eb', borderRadius:8, fontSize:13, fontFamily:'inherit', boxSizing:'border-box', outline:'none', resize:'none', direction:'rtl' }}/>
              <button onClick={addNote} style={{ marginTop:8, padding:'8px 20px', borderRadius:7, border:'none', background:'#1a2c4a', color:'#fff', fontSize:13, fontWeight:700, cursor:'pointer', fontFamily:'inherit' }}>+ הוסף</button>
            </div>

            {/* Existing notes */}
            {contact.notes ? (
              <div style={{ background:'#fff', borderRadius:12, padding:16 }}>
                <div style={{ fontSize:12, fontWeight:700, color:'#6b7280', marginBottom:10 }}>הערות קיימות</div>
                {contact.notes.split('\n').filter(Boolean).map((note, i) => (
                  <div key={i} style={{ padding:'10px 12px', background:'#f9fafb', borderRadius:8, marginBottom:8, fontSize:13, color:'#374151', lineHeight:1.5, borderRight:'3px solid #b5a882' }}>
                    {note}
                  </div>
                ))}
              </div>
            ) : (
              <div style={{ textAlign:'center', padding:'30px', background:'#fff', borderRadius:12, border:'1px dashed #d1d5db' }}>
                <div style={{ fontSize:30, marginBottom:8 }}>📝</div>
                <div style={{ fontSize:13, color:'#9ca3af' }}>אין הערות עדיין</div>
              </div>
            )}
          </div>
        )}
      </div>

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

window.ContactDetailScreen = ContactDetailScreen;
})();
