/**
 * CRM — Vendors Directory (בעלי מקצוע)
 * VendorsScreen: רשימה + פרטים + טופס
 * cloudSave key: 'crm_vendors'
 */
(function () {

// ── Data helpers — משתמש ב-SyncStore (מקור אמת יחיד) ─────────────────────────
function genId() {
  return 'vnd_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
}

function loadVendors() {
  return window.SyncStore ? window.SyncStore.getVendors() : [];
}

function saveVendors(list) {
  if (window.SyncStore) window.SyncStore.saveVendors(list);
}

// ── Constants ──────────────────────────────────────────────────────────────────
const PRIMARY_CATS = ['יועץ', 'קבלן', 'ספק'];

const SECONDARY_CATS = {
  יועץ: ['בטיחות', 'מטבח', 'מיזוג', 'אדריכל', 'מעצב', 'אינסטלציה', 'חשמל', 'תאורה', 'סאונד', 'אקוסטיקה', 'מנדפים', 'איטום', 'אישורי בריאות', 'נגישות'],
  קבלן: ['ראשי', 'משנה', 'נירוסטה', 'נגרות', 'מסגרות', 'חדרי קירור', 'איטום', 'גמר', 'שלט', 'ריצוף', 'גבס'],
  ספק: ['מכשירי מטבח', 'מקררים', 'ברזים', 'מדפים', 'מרכך מים', 'צנרת', 'מזגנים', 'מנדפים', 'מצלמות', 'תקשורת', 'טאבלטים', 'אזעקה', 'כספת'],
};

const CAT_COLORS = {
  יועץ: { bg: '#eff6ff', color: '#2563eb', border: '#bfdbfe' },
  קבלן: { bg: '#fff7ed', color: '#ea580c', border: '#fed7aa' },
  ספק:  { bg: '#f0fdf4', color: '#16a34a', border: '#bbf7d0' },
};

function genId() {
  return 'vnd_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
}

function loadVendors() {
  return window.SyncStore ? window.SyncStore.getVendors() : [];
}

function saveVendors(list) {
  if (window.SyncStore) window.SyncStore.saveVendors(list);
}

// ── StarRating ────────────────────────────────────────────────────────────────
const StarRating = ({ value, onChange, size = 16 }) => (
  <div style={{ display:'flex', gap:2 }}>
    {[1,2,3,4,5].map(n => (
      <span key={n}
        onClick={() => onChange && onChange(n)}
        style={{
          fontSize: size, cursor: onChange ? 'pointer' : 'default',
          color: n <= value ? '#eab308' : '#d1d5db',
          lineHeight: 1,
        }}>★</span>
    ))}
  </div>
);

// ── Shared form primitives (מחוץ לקומפוננטה — למנוע re-mount) ──────────────
const vndInpStyle = {
  width:'100%', padding:'10px 12px', borderRadius:8,
  border:'1.5px solid var(--ybp-border,#e5e7eb)',
  fontSize:15, fontFamily:'Assistant, sans-serif',
  background:'var(--ybp-input-bg,#fff)', color:'var(--ybp-ink,#111827)',
  outline:'none', boxSizing:'border-box', direction:'rtl',
};

const VndField = ({ label, required, error, children }) => (
  <div style={{ display:'flex', flexDirection:'column', gap:4 }}>
    <label style={{ fontSize:12, fontWeight:700, color:'var(--ybp-ink-soft,#374151)', letterSpacing:0.3 }}>
      {label}{required && <span style={{ color:'#dc2626', marginRight:3 }}>*</span>}
    </label>
    {children}
    {error && <span style={{ fontSize:11, color:'#dc2626' }}>{error}</span>}
  </div>
);

// ── VendorForm (Wizard 3 steps) ───────────────────────────────────────────────
const VendorForm = ({ initial, onSave, onCancel }) => {
  const [step, setStep] = React.useState(1);
  const [form, setForm] = React.useState({
    name: '', company: '', phone: '', email: '',
    primaryCat: '', secondaryCats: [],
    rate: '', notes: '', rating: 0, active: true,
    ...(initial || {}),
  });
  const [errors, setErrors] = React.useState({});

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

  const toggleSec = (cat) => {
    const curr = form.secondaryCats || [];
    set('secondaryCats', curr.includes(cat) ? curr.filter(c => c !== cat) : [...curr, cat]);
  };

  const validateStep = (s) => {
    const e = {};
    if (s === 1) {
      if (!form.name.trim()) e.name = 'שדה חובה';
      if (!form.primaryCat) e.primaryCat = 'בחר קטגוריה ראשית';
      if (form.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) e.email = 'פורמט מייל לא תקין';
      if (form.phone && !/^[\d\-+\s]{7,15}$/.test(form.phone)) e.phone = 'טלפון לא תקין';
    }
    if (s === 2) {
      if (!form.secondaryCats || form.secondaryCats.length === 0) e.secondaryCats = 'בחר לפחות קטגוריה אחת';
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const next = () => { if (validateStep(step)) setStep(s => s + 1); };
  const back = () => setStep(s => s - 1);

  const handleSubmit = () => {
    if (!validateStep(3)) return;
    onSave(form);
  };


  const stepLabels = ['פרטים', 'קטגוריות', 'סיכום'];

  return (
    <div style={{ fontFamily:'Assistant, sans-serif', direction:'rtl', minHeight:'100vh', background:'var(--ybp-bg,#f6f7f9)' }}>
      {/* Header */}
      <div style={{
        background:'var(--ybp-panel,#fff)', borderBottom:'1px solid var(--ybp-border,#e5e7eb)',
        padding:'16px 20px', display:'flex', alignItems:'center', gap:12,
      }}>
        <button onClick={onCancel} style={{ background:'none', border:'none', cursor:'pointer', padding:4, display:'flex' }}>
          <Icon name="chevronR" size={22} color="var(--ybp-ink-soft,#6b7280)" />
        </button>
        <div style={{ flex:1 }}>
          <h2 style={{ margin:0, fontSize:18, fontWeight:700, color:'var(--ybp-ink,#111827)' }}>
            {initial ? 'עריכת בעל מקצוע' : 'בעל מקצוע חדש'}
          </h2>
        </div>
        {/* Step indicator */}
        <div style={{ display:'flex', gap:6, alignItems:'center' }}>
          {stepLabels.map((l, i) => (
            <React.Fragment key={i}>
              <div style={{
                width:28, height:28, borderRadius:'50%',
                background: step > i+1 ? '#16a34a' : step === i+1 ? '#1a2c4a' : 'var(--ybp-border,#e5e7eb)',
                color: step >= i+1 ? '#fff' : 'var(--ybp-ink-faint,#9ca3af)',
                display:'flex', alignItems:'center', justifyContent:'center',
                fontSize:12, fontWeight:700, flexShrink:0,
              }}>
                {step > i+1 ? '✓' : i+1}
              </div>
              {i < stepLabels.length - 1 && (
                <div style={{ width:20, height:2, background: step > i+1 ? '#16a34a' : 'var(--ybp-border,#e5e7eb)', borderRadius:1 }} />
              )}
            </React.Fragment>
          ))}
        </div>
      </div>

      <div style={{ padding:20, maxWidth:540, margin:'0 auto' }}>

        {/* ── Step 1: פרטים ── */}
        {step === 1 && (
          <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
            <div style={{ fontSize:13, color:'var(--ybp-ink-faint,#6b7280)', marginBottom:4 }}>פרטים בסיסיים</div>

            <VndField label="שם" required error={errors.name}>
              <input style={{ ...vndInpStyle, borderColor: errors.name ? '#dc2626' : undefined }}
                value={form.name} onChange={e => set('name', e.target.value)}
                placeholder="ישראל ישראלי" />
            </VndField>

            <VndField label="שם חברה">
              <input style={vndInpStyle} value={form.company} onChange={e => set('company', e.target.value)}
                placeholder='לוי בניה בע"מ' />
            </VndField>

            <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:12 }}>
              <VndField label="טלפון" error={errors.phone}>
                <input style={{ ...vndInpStyle, direction:'ltr', textAlign:'right', borderColor: errors.phone ? '#dc2626' : undefined }}
                  value={form.phone} onChange={e => set('phone', e.target.value)}
                  placeholder="050-000-0000" />
              </VndField>
              <VndField label='דוא"ל' error={errors.email}>
                <input style={{ ...vndInpStyle, direction:'ltr', textAlign:'right', borderColor: errors.email ? '#dc2626' : undefined }}
                  value={form.email} onChange={e => set('email', e.target.value)}
                  placeholder="name@company.co.il" />
              </VndField>
            </div>

            <VndField label="קטגוריה ראשית" required error={errors.primaryCat}>
              <div style={{ display:'flex', gap:10 }}>
                {PRIMARY_CATS.map(cat => {
                  const c = CAT_COLORS[cat];
                  const active = form.primaryCat === cat;
                  return (
                    <button key={cat} onClick={() => { set('primaryCat', cat); set('secondaryCats', []); }}
                      style={{
                        flex:1, padding:'10px 8px', borderRadius:9,
                        background: active ? c.bg : 'var(--ybp-panel,#fff)',
                        border: active ? `2px solid ${c.color}` : '1.5px solid var(--ybp-border,#e5e7eb)',
                        color: active ? c.color : 'var(--ybp-ink-soft,#374151)',
                        fontWeight: active ? 700 : 500, fontSize:13, cursor:'pointer',
                        fontFamily:'Assistant, sans-serif',
                      }}
                    >{cat}</button>
                  );
                })}
              </div>
              {errors.primaryCat && <span style={{ fontSize:11, color:'#dc2626' }}>{errors.primaryCat}</span>}
            </VndField>

            <VndField label="תעריף לשעה (₪)">
              <input style={{ ...vndInpStyle, direction:'ltr', textAlign:'right' }}
                type="number" min="0"
                value={form.rate} onChange={e => set('rate', e.target.value)}
                placeholder="0" />
            </VndField>

            <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
              <label style={{ fontSize:12, fontWeight:700, color:'var(--ybp-ink-soft,#374151)', letterSpacing:0.3 }}>דירוג</label>
              <StarRating value={form.rating} onChange={v => set('rating', v)} size={28} />
            </div>
          </div>
        )}

        {/* ── Step 2: קטגוריות משניות ── */}
        {step === 2 && (
          <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
            <div style={{ fontSize:13, color:'var(--ybp-ink-faint,#6b7280)', marginBottom:4 }}>
              בחר קטגוריות משניות עבור <strong>{form.primaryCat}</strong>
            </div>
            {errors.secondaryCats && (
              <div style={{ padding:'10px 14px', borderRadius:8, background:'#fef2f2', color:'#dc2626', fontSize:13 }}>
                {errors.secondaryCats}
              </div>
            )}
            <div style={{ display:'flex', flexWrap:'wrap', gap:8 }}>
              {(SECONDARY_CATS[form.primaryCat] || []).map(cat => {
                const sel = (form.secondaryCats || []).includes(cat);
                return (
                  <button key={cat} onClick={() => toggleSec(cat)} style={{
                    padding:'8px 14px', borderRadius:99,
                    background: sel ? '#1a2c4a' : 'var(--ybp-panel,#fff)',
                    color: sel ? '#fff' : 'var(--ybp-ink,#111827)',
                    border: '1.5px solid ' + (sel ? '#1a2c4a' : 'var(--ybp-border,#e5e7eb)'),
                    fontSize:13, fontWeight: sel ? 700 : 400, cursor:'pointer',
                    fontFamily:'Assistant, sans-serif',
                  }}>{cat}</button>
                );
              })}
            </div>
            {(form.secondaryCats || []).length > 0 && (
              <div style={{ fontSize:12, color:'#16a34a', marginTop:4 }}>
                ✓ נבחרו {form.secondaryCats.length} קטגוריות
              </div>
            )}
          </div>
        )}

        {/* ── Step 3: סיכום + הערות ── */}
        {step === 3 && (
          <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
            <div style={{ fontSize:13, color:'var(--ybp-ink-faint,#6b7280)', marginBottom:4 }}>סיכום ושמירה</div>

            {/* Summary card */}
            <div style={{
              background:'var(--ybp-panel,#fff)', borderRadius:12, padding:16,
              border:'1px solid var(--ybp-border,#e5e7eb)',
              display:'flex', flexDirection:'column', gap:8,
            }}>
              <div style={{ fontWeight:700, fontSize:16, color:'var(--ybp-ink,#111827)' }}>{form.name}</div>
              {form.company && <div style={{ fontSize:13, color:'var(--ybp-ink-soft,#374151)' }}>{form.company}</div>}
              <div style={{ display:'flex', gap:6, flexWrap:'wrap' }}>
                {form.primaryCat && (
                  <span style={{
                    padding:'3px 10px', borderRadius:99, fontSize:12, fontWeight:600,
                    background: CAT_COLORS[form.primaryCat]?.bg, color: CAT_COLORS[form.primaryCat]?.color,
                  }}>{form.primaryCat}</span>
                )}
                {(form.secondaryCats || []).map(c => (
                  <span key={c} style={{
                    padding:'3px 10px', borderRadius:99, fontSize:12,
                    background:'var(--ybp-row-hover,#f3f4f6)', color:'var(--ybp-ink-soft,#374151)',
                  }}>{c}</span>
                ))}
              </div>
              {form.rating > 0 && <StarRating value={form.rating} size={16} />}
            </div>

            <div style={{ display:'flex', flexDirection:'column', gap:4 }}>
              <label style={{ fontSize:12, fontWeight:700, color:'var(--ybp-ink-soft,#374151)', letterSpacing:0.3 }}>הערות</label>
              <textarea
                style={{
                  width:'100%', padding:'10px 12px', borderRadius:8,
                  border:'1.5px solid var(--ybp-border,#e5e7eb)',
                  fontSize:14, fontFamily:'Assistant, sans-serif',
                  background:'var(--ybp-input-bg,#fff)', color:'var(--ybp-ink,#111827)',
                  outline:'none', boxSizing:'border-box', direction:'rtl',
                  minHeight:80, resize:'vertical',
                }}
                value={form.notes} onChange={e => set('notes', e.target.value)}
                placeholder="מידע נוסף, המלצות, היסטוריה..." />
            </div>

            {/* Active toggle */}
            <label style={{ display:'flex', alignItems:'center', gap:8, cursor:'pointer', fontSize:14, color:'var(--ybp-ink,#111827)' }}>
              <div onClick={() => set('active', !form.active)} style={{
                width:40, height:22, borderRadius:11,
                background: form.active ? '#1a2c4a' : '#d1d5db',
                position:'relative', cursor:'pointer', transition:'background 0.2s', flexShrink:0,
              }}>
                <div style={{
                  position:'absolute', top:3,
                  right: form.active ? 3 : undefined, left: form.active ? undefined : 3,
                  width:16, height:16, borderRadius:'50%', background:'#fff', transition:'all 0.2s',
                }} />
              </div>
              בעל מקצוע פעיל
            </label>
          </div>
        )}

        {/* Navigation buttons */}
        <div style={{ display:'flex', gap:10, marginTop:28 }}>
          {step > 1 && (
            <button onClick={back} style={{
              padding:'12px 20px', borderRadius:9,
              background:'var(--ybp-row-hover,#f3f4f6)',
              border:'1px solid var(--ybp-border,#e5e7eb)',
              color:'var(--ybp-ink,#111827)',
              fontSize:14, fontWeight:600, cursor:'pointer', fontFamily:'Assistant, sans-serif',
            }}>הקודם</button>
          )}
          <button
            onClick={step < 3 ? next : handleSubmit}
            style={{
              flex:1, padding:'13px', borderRadius:9,
              background:'#1a2c4a', color:'#fff',
              border:'none', fontSize:15, fontWeight:700, cursor:'pointer',
              fontFamily:'Assistant, sans-serif',
            }}
          >
            {step < 3 ? 'הבא ›' : (initial ? 'שמור שינויים' : 'הוסף בעל מקצוע')}
          </button>
          {step === 1 && (
            <button onClick={onCancel} style={{
              padding:'12px 20px', borderRadius:9,
              background:'var(--ybp-row-hover,#f3f4f6)',
              border:'1px solid var(--ybp-border,#e5e7eb)',
              color:'var(--ybp-ink,#111827)',
              fontSize:14, fontWeight:600, cursor:'pointer', fontFamily:'Assistant, sans-serif',
            }}>ביטול</button>
          )}
        </div>
      </div>
    </div>
  );
};

// ── VendorDetail ──────────────────────────────────────────────────────────────
const VendorDetail = ({ vendorId, onBack, onEdit }) => {
  const vendors = loadVendors();
  const v = vendors.find(x => x.id === vendorId);
  if (!v) return <div style={{ padding:40, textAlign:'center', color:'var(--ybp-ink-faint,#6b7280)', fontFamily:'Assistant,sans-serif' }}>לא נמצא</div>;

  const catColor = CAT_COLORS[v.primaryCat] || CAT_COLORS['ספק'];
  const projects = (window.YBP_DATA || { projects:[] }).projects.filter(p => (v.projectIds||[]).includes(p.id));

  const Row = ({ label, value, isLink, href }) => value ? (
    <div style={{ display:'flex', flexDirection:'column', gap:3, padding:'12px 0', borderBottom:'1px solid var(--ybp-border,#e5e7eb)' }}>
      <span style={{ fontSize:11, fontWeight:700, color:'var(--ybp-ink-faint,#6b7280)', letterSpacing:0.3, textTransform:'uppercase' }}>{label}</span>
      {isLink
        ? <a href={href} style={{ fontSize:14, color:'#1a2c4a', fontWeight:500 }}>{value}</a>
        : <span style={{ fontSize:14, color:'var(--ybp-ink,#111827)', fontWeight:500 }}>{value}</span>
      }
    </div>
  ) : null;

  return (
    <div style={{ fontFamily:'Assistant,sans-serif', direction:'rtl', minHeight:'100vh', background:'var(--ybp-bg,#f6f7f9)' }}>
      {/* Header */}
      <div style={{
        background:'var(--ybp-panel,#fff)', borderBottom:'1px solid var(--ybp-border,#e5e7eb)',
        padding:'16px 20px', display:'flex', alignItems:'center', justifyContent:'space-between',
      }}>
        <div style={{ display:'flex', alignItems:'center', gap:12 }}>
          <button onClick={onBack} style={{ background:'none', border:'none', cursor:'pointer', padding:4, display:'flex' }}>
            <Icon name="chevronR" size={22} color="var(--ybp-ink-soft,#6b7280)" />
          </button>
          <div>
            <h2 style={{ margin:0, fontSize:18, fontWeight:700, color:'var(--ybp-ink,#111827)' }}>{v.name}</h2>
            <div style={{ fontSize:13, color:'var(--ybp-ink-faint,#6b7280)' }}>{v.company || v.primaryCat}</div>
          </div>
        </div>
        <div style={{ display:'flex', gap:8 }}>
          {v.phone && (
            <a href={`https://wa.me/972${v.phone.replace(/^0/, '').replace(/[-\s]/g,'')}`}
              target="_blank" rel="noopener noreferrer"
              style={{
                display:'flex', alignItems:'center', gap:6, padding:'8px 12px', borderRadius:8,
                background:'#f0fdf4', color:'#16a34a', border:'1px solid #bbf7d0',
                fontSize:13, fontWeight:600, textDecoration:'none',
              }}>
              <Icon name="msg" size={15} color="#16a34a" /> WA
            </a>
          )}
          <button onClick={onEdit} style={{
            display:'flex', alignItems:'center', gap:6, padding:'8px 14px', borderRadius:8,
            background:'#1a2c4a', color:'#fff', border:'none', fontSize:13, fontWeight:600, cursor:'pointer',
          }}>
            <Icon name="edit" size={15} color="#fff" /> ערוך
          </button>
        </div>
      </div>

      <div style={{ padding:16, maxWidth:560, margin:'0 auto' }}>
        {/* Category + status */}
        <div style={{ display:'flex', gap:8, marginBottom:16, flexWrap:'wrap' }}>
          <span style={{ padding:'4px 12px', borderRadius:99, fontSize:12, fontWeight:700, background:catColor.bg, color:catColor.color, border:`1px solid ${catColor.border}` }}>
            {v.primaryCat}
          </span>
          {(v.secondaryCats||[]).map(c => (
            <span key={c} style={{ padding:'4px 10px', borderRadius:99, fontSize:11, background:'var(--ybp-row-hover,#f3f4f6)', color:'var(--ybp-ink-soft,#374151)' }}>{c}</span>
          ))}
          <span style={{
            padding:'4px 12px', borderRadius:99, fontSize:12, fontWeight:600,
            background: v.active ? '#f0fdf4' : '#f9fafb', color: v.active ? '#16a34a' : '#6b7280',
          }}>{v.active ? '● פעיל' : '○ לא פעיל'}</span>
        </div>

        {/* Rating */}
        {v.rating > 0 && (
          <div style={{ marginBottom:16 }}>
            <StarRating value={v.rating} size={22} />
          </div>
        )}

        {/* Details */}
        <div style={{ background:'var(--ybp-panel,#fff)', borderRadius:12, padding:'0 20px', border:'1px solid var(--ybp-border,#e5e7eb)', marginBottom:16 }}>
          <Row label="טלפון" value={v.phone} isLink href={`tel:${v.phone}`} />
          <Row label='דוא"ל' value={v.email} isLink href={`mailto:${v.email}`} />
          {v.rate > 0 && <Row label="תעריף לשעה" value={`${v.rate} ₪`} />}
          {v.notes && <Row label="הערות" value={v.notes} />}
        </div>

        {/* Projects */}
        {projects.length > 0 && (
          <div style={{ background:'var(--ybp-panel,#fff)', borderRadius:12, padding:16, border:'1px solid var(--ybp-border,#e5e7eb)', marginBottom:16 }}>
            <h3 style={{ margin:'0 0 12px', fontSize:14, fontWeight:700, color:'var(--ybp-ink,#111827)' }}>פרויקטים פעילים ({projects.length})</h3>
            <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
              {projects.map(p => (
                <div key={p.id} style={{
                  padding:'10px 14px', borderRadius:8, background:'var(--ybp-row-hover,#f6f7f9)',
                  display:'flex', justifyContent:'space-between', alignItems:'center',
                }}>
                  <div style={{ fontWeight:600, fontSize:14, color:'var(--ybp-ink,#111827)' }}>{p.name}</div>
                  <span style={{ padding:'3px 8px', borderRadius:6, fontSize:11, fontWeight:600, background:'#eff6ff', color:'#2563eb' }}>{p.status}</span>
                </div>
              ))}
            </div>
          </div>
        )}

        <div style={{ fontSize:12, color:'var(--ybp-ink-faint,#9ca3af)', textAlign:'center', marginTop:8 }}>
          נוסף {v.createdAt || '—'}
        </div>
      </div>
    </div>
  );
};

// ── VendorsScreen (main) ──────────────────────────────────────────────────────
const VendorsScreen = ({ onBack, filterPrimaryCat }) => {
  const [vendors, setVendors] = React.useState(loadVendors);
  const [view, setView] = React.useState('list');
  const [selectedId, setSelectedId] = React.useState(null);
  const [editVendor, setEditVendor] = React.useState(null);
  const [search, setSearch] = React.useState('');
  const [filterPrimary, setFilterPrimary] = React.useState(filterPrimaryCat || 'הכל');
  const [filterSecondary, setFilterSecondary] = React.useState('');
  const [confirmDelete, setConfirmDelete] = React.useState(null);

  const availableSecondary = React.useMemo(() => {
    if (filterPrimary === 'הכל') {
      return [...new Set(Object.values(SECONDARY_CATS).flat())].sort();
    }
    return SECONDARY_CATS[filterPrimary] || [];
  }, [filterPrimary]);

  const filtered = vendors.filter(v => {
    const matchSearch = !search ||
      v.name.includes(search) || (v.company||'').includes(search) ||
      (v.secondaryCats||[]).some(c => c.includes(search));
    const matchPrimary = filterPrimary === 'הכל' || v.primaryCat === filterPrimary;
    const matchSecondary = !filterSecondary || (v.secondaryCats||[]).includes(filterSecondary);
    return matchSearch && matchPrimary && matchSecondary;
  });

  const persist = (list) => { setVendors(list); saveVendors(list); };

  const handleSave = (form) => {
    if (editVendor && editVendor.id) {
      persist(vendors.map(v => v.id === editVendor.id ? { ...v, ...form } : v));
      window.toastSuccess && window.toastSuccess('בעל מקצוע עודכן');
    } else {
      const newV = { ...form, id: genId(), createdAt: new Date().toLocaleDateString('he-IL'), projectIds:[] };
      persist([newV, ...vendors]);
      window.toastSuccess && window.toastSuccess('בעל מקצוע נוסף');
    }
    setView('list'); setEditVendor(null);
  };

  const handleDelete = (id) => {
    persist(vendors.filter(v => v.id !== id));
    window.toastSuccess && window.toastSuccess('נמחק');
    setView('list'); setConfirmDelete(null);
  };

  // ── form view ──
  if (view === 'form') {
    return <VendorForm initial={editVendor} onSave={handleSave} onCancel={() => { setView(editVendor ? 'detail' : 'list'); setEditVendor(null); }} />;
  }

  // ── detail view ──
  if (view === 'detail' && selectedId) {
    return (
      <div style={{ minHeight:'100vh', background:'var(--ybp-bg,#f6f7f9)' }}>
        <VendorDetail vendorId={selectedId} onBack={() => setView('list')}
          onEdit={() => { setEditVendor(vendors.find(x => x.id === selectedId)); setView('form'); }} />
        <div style={{ padding:'0 16px 32px', maxWidth:560, margin:'0 auto' }}>
          <button onClick={() => setConfirmDelete(selectedId)} style={{
            width:'100%', padding:13, borderRadius:9,
            background:'#fef2f2', color:'#dc2626',
            border:'1px solid #fecaca', fontSize:14, fontWeight:600, cursor:'pointer',
          }}>מחק בעל מקצוע</button>
        </div>
        {confirmDelete && (
          <ConfirmDialog isOpen title="מחק בעל מקצוע?" description="הפעולה אינה הפיכה."
            confirmLabel="מחק" confirmVariant="danger"
            onConfirm={() => handleDelete(confirmDelete)} onCancel={() => setConfirmDelete(null)} />
        )}
      </div>
    );
  }

  // ── list view ──
  const counts = { הכל: vendors.length };
  PRIMARY_CATS.forEach(c => { counts[c] = vendors.filter(v => v.primaryCat === c).length; });

  return (
    <div style={{ minHeight:'100vh', background:'var(--ybp-bg,#f6f7f9)', fontFamily:'Assistant,sans-serif', direction:'rtl' }}>
      {/* Header */}
      <div style={{
        background:'#1a2c4a', color:'#fff',
        padding:'14px 20px', display:'flex', alignItems:'center', justifyContent:'space-between',
        position:'sticky', top:0, zIndex:50,
      }}>
        <div style={{ display:'flex', alignItems:'center', gap:12 }}>
          <button onClick={onBack} style={{ background:'rgba(255,255,255,0.12)', border:'1px solid rgba(255,255,255,0.2)', color:'#fff', cursor:'pointer', padding:'5px 10px', borderRadius:6, fontFamily:'inherit', fontSize:13 }}>
            ← חזרה
          </button>
          <div>
            <h1 style={{ margin:0, fontSize:18, fontWeight:700, color:'#fff' }}>בעלי מקצוע</h1>
            <div style={{ fontSize:12, color:'rgba(255,255,255,0.6)' }}>{vendors.filter(v=>v.active).length} פעילים</div>
          </div>
        </div>
        <button onClick={() => { setEditVendor(null); setView('form'); }} style={{
          display:'flex', alignItems:'center', gap:6, padding:'9px 16px', borderRadius:8,
          background:'rgba(255,255,255,0.15)', color:'#fff', border:'1px solid rgba(255,255,255,0.25)', fontSize:14, fontWeight:600, cursor:'pointer',
        }}>
          <Icon name="plus" size={16} color="#fff" /> חדש
        </button>
      </div>

      {/* Search */}
      <div style={{ padding:'12px 16px 0' }}>
        <div style={{ position:'relative' }}>
          <input
            value={search} onChange={e => setSearch(e.target.value)}
            placeholder="חיפוש לפי שם, חברה, קטגוריה..."
            style={{
              width:'100%', padding:'10px 40px 10px 12px', borderRadius:9,
              border:'1px solid var(--ybp-border,#e5e7eb)', fontSize:14,
              fontFamily:'Assistant,sans-serif', background:'var(--ybp-panel,#fff)',
              color:'var(--ybp-ink,#111827)', outline:'none', boxSizing:'border-box', direction:'rtl',
            }}
          />
        </div>
      </div>

      {/* Primary filter tabs */}
      <div style={{ padding:'10px 16px 0', display:'flex', gap:8, overflowX:'auto' }}>
        {['הכל', ...PRIMARY_CATS].map(cat => {
          const c = CAT_COLORS[cat];
          const active = filterPrimary === cat;
          return (
            <button key={cat} onClick={() => { setFilterPrimary(cat); setFilterSecondary(''); }}
              style={{
                padding:'7px 14px', borderRadius:99, whiteSpace:'nowrap',
                background: active ? (c ? c.bg : '#1a2c4a') : 'var(--ybp-panel,#fff)',
                color: active ? (c ? c.color : '#fff') : 'var(--ybp-ink-soft,#374151)',
                border: '1.5px solid ' + (active ? (c ? c.color : '#1a2c4a') : 'var(--ybp-border,#e5e7eb)'),
                fontSize:13, fontWeight: active ? 700 : 500, cursor:'pointer',
                fontFamily:'Assistant,sans-serif', flexShrink:0,
              }}>
              {cat} {counts[cat] !== undefined ? `(${counts[cat]})` : ''}
            </button>
          );
        })}
      </div>

      {/* Secondary filter chips */}
      {filterPrimary !== 'הכל' && availableSecondary.length > 0 && (
        <div style={{ padding:'8px 16px 0', display:'flex', gap:6, overflowX:'auto', paddingBottom:2 }}>
          <button onClick={() => setFilterSecondary('')} style={{
            padding:'5px 12px', borderRadius:99, whiteSpace:'nowrap',
            background: !filterSecondary ? '#1a2c4a' : 'transparent',
            color: !filterSecondary ? '#fff' : 'var(--ybp-ink-faint,#6b7280)',
            border:'1px solid ' + (!filterSecondary ? '#1a2c4a' : 'var(--ybp-border,#e5e7eb)'),
            fontSize:12, cursor:'pointer', fontFamily:'Assistant,sans-serif', flexShrink:0,
          }}>הכל</button>
          {availableSecondary.map(cat => (
            <button key={cat} onClick={() => setFilterSecondary(cat === filterSecondary ? '' : cat)} style={{
              padding:'5px 12px', borderRadius:99, whiteSpace:'nowrap',
              background: filterSecondary === cat ? '#1a2c4a' : 'transparent',
              color: filterSecondary === cat ? '#fff' : 'var(--ybp-ink-faint,#6b7280)',
              border:'1px solid ' + (filterSecondary === cat ? '#1a2c4a' : 'var(--ybp-border,#e5e7eb)'),
              fontSize:12, cursor:'pointer', fontFamily:'Assistant,sans-serif', flexShrink:0,
            }}>{cat}</button>
          ))}
        </div>
      )}

      {/* List */}
      <div style={{ padding:'12px 16px 32px' }}>
        {filtered.length === 0 ? (
          <EmptyState
            icon="vendor"
            title={search || filterSecondary ? 'לא נמצאו בעלי מקצוע' : 'אין בעלי מקצוע עדיין'}
            description={search || filterSecondary ? 'נסה לנקות פילטרים' : 'הוסף בעלי מקצוע לספרייה'}
            primaryAction={search || filterSecondary
              ? { label:'נקה פילטרים', onClick:() => { setSearch(''); setFilterSecondary(''); }}
              : { label:'+ הוסף', onClick:() => setView('form') }
            }
          />
        ) : (
          filtered.map(v => {
            const c = CAT_COLORS[v.primaryCat] || CAT_COLORS['ספק'];
            return (
              <div key={v.id}
                onClick={() => { setSelectedId(v.id); setView('detail'); }}
                style={{
                  background:'var(--ybp-panel,#fff)', borderRadius:10, padding:'14px 16px',
                  marginBottom:10, border:'1px solid var(--ybp-border,#e5e7eb)',
                  cursor:'pointer', display:'flex', gap:14, alignItems:'flex-start',
                }}
                onMouseEnter={e => e.currentTarget.style.boxShadow = '0 4px 12px rgba(0,0,0,0.08)'}
                onMouseLeave={e => e.currentTarget.style.boxShadow = 'none'}
              >
                {/* Category color dot */}
                <div style={{
                  width:44, height:44, borderRadius:10,
                  background: c.bg, border:`1.5px solid ${c.border}`,
                  display:'flex', alignItems:'center', justifyContent:'center',
                  fontSize:17, fontWeight:700, color: c.color, flexShrink:0,
                }}>
                  {v.name.charAt(0)}
                </div>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:8 }}>
                    <div style={{ fontWeight:700, fontSize:15, color:'var(--ybp-ink,#111827)' }}>{v.name}</div>
                    <div style={{ display:'flex', gap:6, flexShrink:0, alignItems:'center' }}>
                      {v.rating > 0 && <span style={{ fontSize:12, color:'#eab308', fontWeight:600 }}>{'★'.repeat(v.rating)}</span>}
                      <span style={{
                        padding:'2px 8px', borderRadius:99, fontSize:11, fontWeight:600,
                        background:c.bg, color:c.color,
                      }}>{v.primaryCat}</span>
                    </div>
                  </div>
                  {v.company && <div style={{ fontSize:13, color:'var(--ybp-ink-soft,#374151)', marginTop:2 }}>{v.company}</div>}
                  {/* Secondary cats */}
                  <div style={{ display:'flex', gap:4, flexWrap:'wrap', marginTop:6 }}>
                    {(v.secondaryCats||[]).slice(0,3).map(cat => (
                      <span key={cat} style={{
                        padding:'2px 8px', borderRadius:99, fontSize:11,
                        background:'var(--ybp-row-hover,#f3f4f6)', color:'var(--ybp-ink-faint,#6b7280)',
                      }}>{cat}</span>
                    ))}
                    {(v.secondaryCats||[]).length > 3 && (
                      <span style={{ fontSize:11, color:'var(--ybp-ink-faint,#9ca3af)' }}>+{v.secondaryCats.length-3}</span>
                    )}
                  </div>
                  {v.phone && (
                    <div style={{ fontSize:12, color:'var(--ybp-ink-faint,#6b7280)', marginTop:5, display:'flex', alignItems:'center', gap:4 }}>
                      <Icon name="phone" size={12} color="var(--ybp-ink-faint,#9ca3af)" />
                      {v.phone}
                    </div>
                  )}
                </div>
              </div>
            );
          })
        )}
      </div>
    </div>
  );
};

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