/**
 * NewProjectWizard — Wizard הקמת פרויקט חדש
 * 3 שלבים: פרטי פרויקט → לקוח + קבלן → סיכום + אישור
 * בסיום: יוצר פרויקט, חוברת אוטומטית, שולח WEBHOOK → Make → Drive
 */
(function () {
const { useState, useEffect, useRef } = React;

const NAVY  = '#1a2c4a';
const GOLD  = '#b5a882';
const GREEN = '#16a34a';
const GRAY  = '#6b7280';
const RED   = '#dc2626';
const BORDER = '#e5e7eb';

// ── Webhook ───────────────────────────────────────────────────────────────────
const NEW_PROJECT_WEBHOOK_KEY = 'PLACEHOLDER_NEW_PROJECT_SETUP';
const NEW_PROJECT_WEBHOOK_FALLBACK = 'https://hook.eu2.make.com/d1syt3rlghwb7eomyo2wwxabuxxobcqx';

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

// אתחול URL בsettings אם עדיין לא הוזן
;(function seedNewProjectWebhook() {
  try {
    const s = JSON.parse(localStorage.getItem('ybp_settings') || '{}');
    if (!(s.webhooks || {})[NEW_PROJECT_WEBHOOK_KEY]) {
      s.webhooks = { ...(s.webhooks || {}), [NEW_PROJECT_WEBHOOK_KEY]: NEW_PROJECT_WEBHOOK_FALLBACK };
      localStorage.setItem('ybp_settings', JSON.stringify(s));
    }
  } catch {}
})();

// ── Project types ─────────────────────────────────────────────────────────────
const PROJECT_TYPES = [
  { k: 'restaurant', label: 'מסעדה / בית קפה', icon: '🍽️' },
  { k: 'office',     label: 'משרדים',           icon: '🏢' },
  { k: 'retail',     label: 'מסחרי / חנות',     icon: '🏪' },
  { k: 'apartment',  label: 'מגורים / דירה',    icon: '🏠' },
  { k: 'industrial', label: 'תעשייה / מחסן',    icon: '🏭' },
  { k: 'other',      label: 'אחר',              icon: '📋' },
];

// ── Auto project number ───────────────────────────────────────────────────────
function generateProjectNumber() {
  const year = new Date().getFullYear();
  const existing = window.YBP_DATA?.projects || [];
  const thisYear = existing.filter(p => p.projectNumber && p.projectNumber.startsWith(`YBP-${year}`));
  const next = String(thisYear.length + 1).padStart(3, '0');
  return `YBP-${year}-${next}`;
}

// ── Field component ───────────────────────────────────────────────────────────
const Field = ({ label, required, children, error, hint }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 5 }}>
    <label style={{
      fontSize: 13, fontWeight: 600,
      color: 'var(--ybp-ink,#111827)',
      display: 'flex', gap: 4, alignItems: 'center',
    }}>
      {label}
      {required && <span style={{ color: RED, fontSize: 12 }}>*</span>}
    </label>
    {children}
    {hint && !error && <div style={{ fontSize: 11, color: GRAY }}>{hint}</div>}
    {error && <div style={{ fontSize: 11, color: RED }}>{error}</div>}
  </div>
);

const inputStyle = (hasError) => ({
  width: '100%', padding: '10px 12px', borderRadius: 8, boxSizing: 'border-box',
  border: `1px solid ${hasError ? RED : BORDER}`,
  fontSize: 14, fontFamily: 'Assistant, sans-serif',
  background: 'var(--ybp-input-bg,#fff)',
  color: 'var(--ybp-ink,#111827)',
  outline: 'none',
  direction: 'rtl',
});

const selectStyle = (hasError) => ({
  ...inputStyle(hasError),
  cursor: 'pointer',
  appearance: 'none',
  WebkitAppearance: 'none',
  backgroundImage: `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8'%3E%3Cpath d='M1 1l5 5 5-5' stroke='%236b7280' stroke-width='1.5' fill='none' stroke-linecap='round'/%3E%3C/svg%3E")`,
  backgroundRepeat: 'no-repeat',
  backgroundPosition: 'left 12px center',
  paddingLeft: 32,
});

// ── Step indicator ────────────────────────────────────────────────────────────
const StepBar = ({ step, total }) => (
  <div style={{ display: 'flex', gap: 6, alignItems: 'center', justifyContent: 'center', padding: '0 0 4px' }}>
    {Array.from({ length: total }).map((_, i) => (
      <div key={i} style={{
        height: 4, flex: 1, maxWidth: 60, borderRadius: 99,
        background: i < step ? NAVY : i === step ? GOLD : BORDER,
        transition: 'background 0.3s',
      }} />
    ))}
  </div>
);

// ── PM helpers (v3.9.0.43) ────────────────────────────────────────────────────
// pmKey = החלק לפני ה-@ במייל, lowercase — תואם בדיוק ל-ybp_my_pmkey() ב-Supabase
const pmKeyOf = (email) => (email || '').split('@')[0].toLowerCase();
const ADMIN_EMAILS = ['nathan@ybprojects.com','yuval@ybprojects.com','barak@ybprojects.com'];
const isAdminUser = (u) => {
  if (!u) return false;
  if (u.role === 'admin') return true;
  return ADMIN_EMAILS.includes((u.email || '').toLowerCase());
};

// ── Step 1: פרטי הפרויקט ──────────────────────────────────────────────────────
const Step1 = ({ data, onChange, errors, profiles, currentUser, isAdmin }) => {
  const projectNumber = useRef(generateProjectNumber());

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      <div style={{
        background: 'var(--ybp-row-hover,#f6f7f9)',
        borderRadius: 10, padding: '12px 16px',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
      }}>
        <div>
          <div style={{ fontSize: 11, color: GRAY, fontWeight: 600, letterSpacing: 0.5, textTransform: 'uppercase' }}>מספר פרויקט</div>
          <div style={{ fontSize: 20, fontWeight: 800, color: NAVY, letterSpacing: 0.5, marginTop: 2 }}>
            {projectNumber.current}
          </div>
        </div>
        <div style={{
          background: NAVY, color: '#fff',
          width: 44, height: 44, borderRadius: 10,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 22,
        }}>🏗️</div>
      </div>

      <Field label="שם הפרויקט" required error={errors.name}>
        <input
          value={data.name || ''}
          onChange={e => onChange('name', e.target.value)}
          placeholder="למשל: מסעדת NOBU תל אביב"
          style={inputStyle(!!errors.name)}
        />
      </Field>

      <Field label="סוג פרויקט" required error={errors.type}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
          {PROJECT_TYPES.map(t => (
            <button key={t.k} onClick={() => onChange('type', t.k)} style={{
              padding: '10px 8px', borderRadius: 8, cursor: 'pointer',
              border: `2px solid ${data.type === t.k ? NAVY : BORDER}`,
              background: data.type === t.k ? '#eef2ff' : 'var(--ybp-input-bg,#fff)',
              color: data.type === t.k ? NAVY : 'var(--ybp-ink,#111827)',
              fontFamily: 'Assistant, sans-serif', fontWeight: 600, fontSize: 12,
              display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
              transition: 'all 0.15s',
            }}>
              <span style={{ fontSize: 20 }}>{t.icon}</span>
              <span>{t.label}</span>
            </button>
          ))}
        </div>
      </Field>

      <Field label="כתובת הפרויקט" required error={errors.address}>
        <input
          value={data.address || ''}
          onChange={e => onChange('address', e.target.value)}
          placeholder="רחוב הירקון 99, תל אביב"
          style={inputStyle(!!errors.address)}
        />
      </Field>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <Field label="גוש" hint="לא חובה">
          <input
            value={data.block || ''}
            onChange={e => onChange('block', e.target.value)}
            placeholder="למשל: 6620"
            style={inputStyle(false)}
          />
        </Field>
        <Field label="חלקה" hint="לא חובה">
          <input
            value={data.parcel || ''}
            onChange={e => onChange('parcel', e.target.value)}
            placeholder="למשל: 47"
            style={inputStyle(false)}
          />
        </Field>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
        <Field label='שטח (מ"ר)' required error={errors.area}>
          <input
            type="number"
            value={data.area || ''}
            onChange={e => onChange('area', e.target.value)}
            placeholder="למשל: 450"
            min="1"
            style={inputStyle(!!errors.area)}
          />
        </Field>
        <Field label="תאריך יעד לסיום" required error={errors.endDate}>
          <input
            type="date"
            value={data.endDate || ''}
            onChange={e => onChange('endDate', e.target.value)}
            style={inputStyle(!!errors.endDate)}
          />
        </Field>
      </div>

      <Field label="תקציב ראשוני (₪)" hint="לא חובה — ניתן לעדכן בהמשך">
        <div style={{ position: 'relative' }}>
          <input
            type="number"
            value={data.budget || ''}
            onChange={e => onChange('budget', e.target.value)}
            placeholder="למשל: 4500000"
            min="0"
            style={{ ...inputStyle(false), paddingLeft: 36 }}
          />
          <span style={{
            position: 'absolute', left: 12, top: '50%', transform: 'translateY(-50%)',
            color: GRAY, fontWeight: 700, fontSize: 14,
          }}>₪</span>
        </div>
      </Field>

      {/* ── מנהל פרויקט אחראי — admin בלבד יכול לבחור PM אחר (v3.9.0.43) ── */}
      <Field label="מנהל פרויקט אחראי" required hint={isAdmin ? 'admin: ניתן להקצות לכל מנהל' : 'מוקצה אוטומטית עליך'}>
        {isAdmin ? (
          <select
            value={data.pmKey || ''}
            onChange={e => {
              const p = profiles.find(x => pmKeyOf(x.email) === e.target.value);
              if (!p) return;
              const key = pmKeyOf(p.email);
              onChange('pmKey', key);
              onChange('pm',    p.full_name || p.email);
              onChange('pms',   [key]);
            }}
            style={selectStyle(false)}
          >
            {(profiles.length === 0) && <option value="">— טוען רשימת מנהלים… —</option>}
            {profiles.map(p => (
              <option key={p.id} value={pmKeyOf(p.email)}>
                {(p.full_name || p.email)} · {p.email}
              </option>
            ))}
          </select>
        ) : (
          <div style={{
            ...inputStyle(false),
            background: 'var(--ybp-row-hover,#f6f7f9)',
            color: 'var(--ybp-ink-soft,#6b7280)',
            cursor: 'default',
          }}>
            {data.pm || (currentUser && currentUser.name) || '—'}
          </div>
        )}
      </Field>
    </div>
  );
};

// ── ContactAutocomplete (v3.9.0.46) — חיפוש חופשי בשם/חברה/תפקיד, dropdown מסונן ─
const ContactAutocomplete = ({ value, onSelect, contacts, placeholder, errorBorder }) => {
  const [query, setQuery] = useState('');
  const [open, setOpen]   = useState(false);
  const selected = value ? contacts.find(c => c.id === value) : null;
  const inputDisplay = selected
    ? `${selected.name}${selected.company ? ' · ' + selected.company : ''}${selected.role ? ' · ' + selected.role : ''}`
    : query;
  const q = query.trim().toLowerCase();
  const filtered = !q ? contacts.slice(0, 50) : contacts.filter(c =>
    (c.name || '').toLowerCase().includes(q) ||
    (c.company || '').toLowerCase().includes(q) ||
    (c.role || '').toLowerCase().includes(q)
  ).slice(0, 50);
  return (
    <div style={{ position: 'relative' }}>
      <input type="text" value={inputDisplay}
        onFocus={() => { setOpen(true); if (selected) { setQuery(''); } }}
        onBlur={() => setTimeout(() => setOpen(false), 150)}
        onChange={e => { setQuery(e.target.value); if (selected) onSelect(null); setOpen(true); }}
        placeholder={placeholder}
        style={{ ...inputStyle(false), border: `1px solid ${errorBorder ? RED : BORDER}` }}/>
      {open && filtered.length > 0 && (
        <div style={{ position:'absolute', top:'100%', insetInlineStart:0, insetInlineEnd:0, marginTop:4,
          background:'#fff', border:`1px solid ${BORDER}`, borderRadius:8, maxHeight:240, overflowY:'auto',
          zIndex:50, boxShadow:'0 8px 24px rgba(0,0,0,0.08)' }}>
          {filtered.map(c => (
            <div key={c.id} onMouseDown={(e) => { e.preventDefault(); onSelect(c.id); setQuery(''); setOpen(false); }}
              style={{ padding:'8px 12px', cursor:'pointer', fontSize:13, borderBottom:'1px solid #f3f4f6', direction:'rtl' }}
              onMouseEnter={e => e.currentTarget.style.background = '#f9fafb'}
              onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
              <div style={{ fontWeight:600, color:'#1f2937' }}>{c.name}</div>
              <div style={{ fontSize:11, color:GRAY }}>{[c.company, c.role].filter(Boolean).join(' · ') || '—'}</div>
            </div>
          ))}
        </div>
      )}
      {open && q && filtered.length === 0 && (
        <div style={{ position:'absolute', top:'100%', insetInlineStart:0, insetInlineEnd:0, marginTop:4,
          background:'#fff', border:`1px solid ${BORDER}`, borderRadius:8, padding:'8px 12px',
          fontSize:12, color:GRAY, zIndex:50 }}>אין התאמה — בחר "+ חדש"</div>
      )}
    </div>
  );
};

// ── Step 2: לקוח + קבלן ──────────────────────────────────────────────────────
const Step2 = ({ data, onChange, errors }) => {
  const [showNewClient, setShowNewClient] = useState(false);
  const [showContractor, setShowContractor] = useState(!!data.contractorId || !!data.contractorName);

  // v3.9.0.44 — קריאה מ-ContactsStore (Supabase contacts). המקור הקודם (SyncStore) ריק.
  const [allContacts, setAllContacts] = useState([]);
  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        if (!window.ContactsStore || !window.ContactsStore.listAll) return;
        const list = await window.ContactsStore.listAll();
        if (!cancelled) setAllContacts(list || []);
      } catch (e) { console.warn('[Step2] ContactsStore.listAll failed:', e); }
    })();
    return () => { cancelled = true; };
  }, []);

  // v3.9.0.46 — לקוחות וקבלנים: כל אנשי הקשר עם autocomplete; הסינון הקודם "כולל 'קבלן'"
  // הפיל ספקים שהוגדרו כ"נגרות"/"מסגרות"/"חשמל" וכו'. עדיף לחפש על כל הספרייה.
  const customers = allContacts;
  const contractors = allContacts;

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

      {/* לקוח */}
      <div style={{
        // v3.9.0.47 — הוסר overflow:hidden כדי שה-dropdown של ה-autocomplete לא ייחתך.
        // borderRadius של הכותרת מטופל במקום בהגדרת הכותרת עצמה.
        border: `1px solid ${BORDER}`, borderRadius: 12,
      }}>
        <div style={{
          background: 'var(--ybp-row-hover,#f6f7f9)',
          padding: '12px 16px', borderBottom: `1px solid ${BORDER}`,
          borderRadius: '12px 12px 0 0',
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        }}>
          <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--ybp-ink,#111827)' }}>
            👤 לקוח <span style={{ color: RED, fontSize: 12 }}>*</span>
          </div>
          <button onClick={() => setShowNewClient(v => !v)} style={{
            background: 'none', border: `1px solid ${BORDER}`,
            padding: '4px 10px', borderRadius: 6, fontSize: 12, fontWeight: 600,
            cursor: 'pointer', fontFamily: 'Assistant, sans-serif',
            color: 'var(--ybp-ink-soft,#6b7280)',
          }}>
            {showNewClient ? '← בחר קיים' : '+ לקוח חדש'}
          </button>
        </div>
        <div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 12 }}>
          {!showNewClient ? (
            <Field label="" error={errors.clientId}>
              {customers.length > 0 ? (
                <>
                  {/* v3.9.0.46 — autocomplete במקום select ארוך */}
                  <ContactAutocomplete
                    value={data.clientId || ''} contacts={customers}
                    placeholder="הקלד שם, חברה או תפקיד..."
                    errorBorder={!!errors.clientId}
                    onSelect={(id) => {
                      onChange('clientId', id || '');
                      const c = id ? customers.find(x => x.id === id) : null;
                      onChange('clientName',    c ? (c.company || c.name || '') : '');
                      onChange('clientContact', c ? (c.name || '') : '');
                      onChange('clientPhone',   c ? (c.phone || c.office_phone || '') : '');
                      onChange('clientEmail',   c ? (c.email || c.office_email || '') : '');
                    }}/>
                  {data.clientId && (() => {
                    const c = customers.find(x => x.id === data.clientId);
                    if (!c) return null;
                    const rows = [
                      ['חברה',    c.company || '—'],
                      ['איש קשר', c.name || '—'],
                      ['תפקיד',   c.role || '—'],
                      ['טלפון',   c.phone || c.office_phone || '—'],
                      ['אימייל',  c.email || c.office_email || '—'],
                    ];
                    return (
                      <div style={{
                        marginTop: 8, padding: '10px 12px',
                        background: 'var(--ybp-row-hover,#f6f7f9)',
                        border: `1px solid ${BORDER}`, borderRadius: 8,
                        display: 'grid', gridTemplateColumns: '90px 1fr', rowGap: 4, columnGap: 10,
                        fontSize: 12,
                      }}>
                        {rows.map(([k,v]) => (
                          <React.Fragment key={k}>
                            <div style={{ color: GRAY, fontWeight: 600 }}>{k}</div>
                            <div style={{ color: 'var(--ybp-ink,#111827)' }}>{v}</div>
                          </React.Fragment>
                        ))}
                      </div>
                    );
                  })()}
                </>
              ) : (
                <div style={{ fontSize: 13, color: GRAY, padding: '8px 0' }}>
                  אין לקוחות ב-CRM —{' '}
                  <button onClick={() => setShowNewClient(true)} style={{
                    background: 'none', border: 'none', color: NAVY,
                    cursor: 'pointer', fontFamily: 'Assistant, sans-serif',
                    fontSize: 13, fontWeight: 600, padding: 0, textDecoration: 'underline',
                  }}>הוסף לקוח חדש</button>
                </div>
              )}
            </Field>
          ) : (
            <>
              <Field label="שם הלקוח / החברה" required error={errors.clientName}>
                <input
                  value={data.clientName || ''}
                  onChange={e => onChange('clientName', e.target.value)}
                  placeholder="למשל: קבוצת נובו ישראל"
                  style={inputStyle(!!errors.clientName)}
                />
              </Field>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <Field label="איש קשר">
                  <input
                    value={data.clientContact || ''}
                    onChange={e => onChange('clientContact', e.target.value)}
                    placeholder="שם מלא"
                    style={inputStyle(false)}
                  />
                </Field>
                <Field label="טלפון">
                  <input
                    value={data.clientPhone || ''}
                    onChange={e => onChange('clientPhone', e.target.value)}
                    placeholder="050-0000000"
                    style={{ ...inputStyle(false), direction: 'ltr', textAlign: 'right' }}
                  />
                </Field>
              </div>
              <Field label="אימייל">
                <input
                  value={data.clientEmail || ''}
                  onChange={e => onChange('clientEmail', e.target.value)}
                  placeholder="client@example.com"
                  style={{ ...inputStyle(false), direction: 'ltr', textAlign: 'right' }}
                />
              </Field>
            </>
          )}
        </div>
      </div>

      {/* קבלן */}
      <div style={{
        // v3.9.0.47 — הוסר overflow:hidden כדי שה-dropdown של ה-autocomplete לא ייחתך.
        border: `1px solid ${BORDER}`, borderRadius: 12,
      }}>
        <div style={{
          background: 'var(--ybp-row-hover,#f6f7f9)',
          padding: '12px 16px', borderBottom: showContractor ? `1px solid ${BORDER}` : 'none',
          borderRadius: showContractor ? '12px 12px 0 0' : 12,
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        }}>
          <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--ybp-ink,#111827)' }}>
            🦺 קבלן ראשי
            <span style={{ fontSize: 11, color: GRAY, fontWeight: 400, marginRight: 6 }}>— לא חובה</span>
          </div>
          <button onClick={() => setShowContractor(v => !v)} style={{
            background: showContractor ? '#fef2f2' : 'none',
            border: `1px solid ${showContractor ? '#fecaca' : BORDER}`,
            padding: '4px 10px', borderRadius: 6, fontSize: 12, fontWeight: 600,
            cursor: 'pointer', fontFamily: 'Assistant, sans-serif',
            color: showContractor ? RED : 'var(--ybp-ink-soft,#6b7280)',
          }}>
            {showContractor ? '✕ הסר' : '+ הוסף קבלן'}
          </button>
        </div>
        {showContractor && (
          <div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 12 }}>
            {contractors.length > 0 ? (
              <Field label="בחר קבלן מה-Vendors">
                <>
                  {/* v3.9.0.46 — autocomplete במקום select ארוך */}
                  <ContactAutocomplete
                    value={data.contractorId || ''} contacts={contractors}
                    placeholder="הקלד שם, חברה או תפקיד..."
                    errorBorder={false}
                    onSelect={(id) => {
                      onChange('contractorId', id || '');
                      const v = id ? contractors.find(x => x.id === id) : null;
                      onChange('contractorName',  v ? (v.company || v.name || '') : '');
                      onChange('contractorPhone', v ? (v.phone || v.office_phone || '') : '');
                    }}/>
                  {data.contractorId && (() => {
                    const v = contractors.find(x => x.id === data.contractorId);
                    if (!v) return null;
                    return (
                      <div style={{
                        marginTop: 8, padding: '10px 12px',
                        background: 'var(--ybp-row-hover,#f6f7f9)',
                        border: `1px solid ${BORDER}`, borderRadius: 8,
                        display: 'grid', gridTemplateColumns: '90px 1fr', rowGap: 4, columnGap: 10,
                        fontSize: 12,
                      }}>
                        <div style={{ color: GRAY, fontWeight: 600 }}>חברה</div>
                        <div>{v.company || '—'}</div>
                        <div style={{ color: GRAY, fontWeight: 600 }}>איש קשר</div>
                        <div>{v.name || '—'}</div>
                        <div style={{ color: GRAY, fontWeight: 600 }}>תפקיד</div>
                        <div>{v.role || '—'}</div>
                        <div style={{ color: GRAY, fontWeight: 600 }}>טלפון</div>
                        <div>{v.phone || v.office_phone || '—'}</div>
                        <div style={{ color: GRAY, fontWeight: 600 }}>אימייל</div>
                        <div>{v.email || v.office_email || '—'}</div>
                      </div>
                    );
                  })()}
                </>
              </Field>
            ) : null}
            <Field label={contractors.length > 0 ? 'או הזן שם קבלן ידנית' : 'שם הקבלן'}>
              <input
                value={data.contractorName || ''}
                onChange={e => onChange('contractorName', e.target.value)}
                placeholder="שם הקבלן הראשי"
                style={inputStyle(false)}
              />
            </Field>
            <Field label="טלפון קבלן" hint="לא חובה">
              <input
                value={data.contractorPhone || ''}
                onChange={e => onChange('contractorPhone', e.target.value)}
                placeholder="050-0000000"
                style={{ ...inputStyle(false), direction: 'ltr', textAlign: 'right' }}
              />
            </Field>
          </div>
        )}
      </div>

    </div>
  );
};

// ── Step 3: סיכום + אישור ────────────────────────────────────────────────────
const Step3 = ({ data }) => {
  const typeObj = PROJECT_TYPES.find(t => t.k === data.type);
  const fmtBudget = n => n ? Number(n).toLocaleString('he-IL') + ' ₪' : '—';
  const fmtDate = s => s ? new Date(s).toLocaleDateString('he-IL', { day:'2-digit', month:'2-digit', year:'numeric' }) : '—';

  const rows = [
    { label: 'מספר פרויקט', value: data.projectNumber, highlight: true },
    { label: 'שם הפרויקט', value: data.name },
    { label: 'סוג', value: typeObj ? `${typeObj.icon} ${typeObj.label}` : '—' },
    { label: 'כתובת', value: data.address },
    ...(data.block || data.parcel ? [{ label: 'גוש/חלקה', value: `${data.block || '—'} / ${data.parcel || '—'}` }] : []),
    { label: 'שטח', value: data.area ? `${data.area} מ"ר` : '—' },
    { label: 'תאריך יעד', value: fmtDate(data.endDate) },
    { label: 'תקציב ראשוני', value: fmtBudget(data.budget) },
    { label: 'לקוח', value: data.clientName || '—' },
    ...(data.contractorName ? [{ label: 'קבלן ראשי', value: data.contractorName }] : []),
  ];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
      <div style={{
        background: '#f0fdf4', border: '1px solid #bbf7d0',
        borderRadius: 10, padding: '12px 16px',
        display: 'flex', gap: 10, alignItems: 'flex-start',
      }}>
        <span style={{ fontSize: 20, flexShrink: 0 }}>✅</span>
        <div>
          <div style={{ fontSize: 14, fontWeight: 700, color: '#166534' }}>הכל מוכן ליצירת הפרויקט</div>
          <div style={{ fontSize: 12, color: '#15803d', marginTop: 2 }}>
            לאחר האישור: הסביבה תיצור, חוברת הפרויקט תיפתח, ותיקיית Drive תוקם
          </div>
        </div>
      </div>

      <div style={{
        background: 'var(--ybp-panel,#fff)',
        border: `1px solid ${BORDER}`, borderRadius: 12, overflow: 'hidden',
      }}>
        {rows.map((r, i) => (
          <div key={i} style={{
            display: 'grid', gridTemplateColumns: '120px 1fr',
            padding: '11px 16px', gap: 12, alignItems: 'center',
            borderBottom: i < rows.length - 1 ? `1px solid ${BORDER}` : 'none',
            background: r.highlight ? '#eff6ff' : 'transparent',
          }}>
            <div style={{ fontSize: 12, color: GRAY, fontWeight: 600 }}>{r.label}</div>
            <div style={{
              fontSize: 13, fontWeight: r.highlight ? 800 : 600,
              color: r.highlight ? NAVY : 'var(--ybp-ink,#111827)',
              letterSpacing: r.highlight ? 0.5 : 0,
            }}>{r.value}</div>
          </div>
        ))}
      </div>

      <div style={{
        background: '#fffbeb', border: '1px solid #fde68a',
        borderRadius: 10, padding: '10px 14px',
        fontSize: 12, color: '#92400e',
        display: 'flex', gap: 8, alignItems: 'flex-start',
      }}>
        <span>⚡</span>
        <span>לאחר היצירה תועבר אוטומטית לחוברת הפרויקט — שם תוכל לערוך, להוסיף ולמחוק נתונים</span>
      </div>
    </div>
  );
};

// ── Main Wizard ───────────────────────────────────────────────────────────────
const NewProjectWizard = ({ onClose, onCreated }) => {
  const [step, setStep] = useState(0);
  const [loading, setLoading] = useState(false);
  const currentUser = (window.YBP_AUTH && window.YBP_AUTH.getCurrentUser) ? window.YBP_AUTH.getCurrentUser() : null;
  const isAdmin     = isAdminUser(currentUser);
  const [profiles, setProfiles] = useState([]);
  const [data, setData] = useState(() => {
    const myKey  = currentUser ? pmKeyOf(currentUser.email) : '';
    const myName = currentUser?.name || '';
    return {
      projectNumber: generateProjectNumber(),
      pm:    myName,
      pmKey: myKey,
      pms:   myKey ? [myKey] : [],
    };
  });
  const [errors, setErrors] = useState({});

  // טען רשימת מנהלי פרויקט (profiles) — נחוץ לבורר PM ב-Step1 (admin בלבד)
  // v3.9.0.44 — טען רשימת מנהלי פרויקט מטבלת contacts (role='ניהול פרויקט').
  // המקור הקודם (profiles) הכיל רק 2 משתמשים שהתחברו לאפליקציה; contacts מכיל את כל ה-PMs (~7).
  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        if (!window.ContactsStore || !window.ContactsStore.listProjectManagers) return;
        const rows = await window.ContactsStore.listProjectManagers();
        if (cancelled) return;
        // fallback: ודא שהמשתמש הנוכחי תמיד ברשימה (edge case אם חסר ב-DB)
        let list = rows || [];
        if (currentUser && currentUser.email) {
          const has = list.some(p => (p.email || '').toLowerCase() === currentUser.email.toLowerCase());
          if (!has) {
            list = [{ id: 'self', email: currentUser.email, full_name: currentUser.name || currentUser.email }, ...list];
          }
        }
        setProfiles(list);
        if (currentUser) {
          const mine = list.find(p => (p.email || '').toLowerCase() === (currentUser.email || '').toLowerCase());
          if (mine && mine.full_name && mine.full_name !== data.pm) {
            setData(d => ({ ...d, pm: mine.full_name }));
          }
        }
      } catch (e) { console.warn('[NewProjectWizard] listProjectManagers failed:', e); }
    })();
    return () => { cancelled = true; };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const onChange = (key, val) => {
    setData(d => ({ ...d, [key]: val }));
    if (errors[key]) setErrors(e => ({ ...e, [key]: null }));
  };

  // ── Validation ──
  const validate = () => {
    const errs = {};
    if (step === 0) {
      if (!data.name?.trim()) errs.name = 'שדה חובה';
      if (!data.type) errs.type = 'יש לבחור סוג פרויקט';
      if (!data.address?.trim()) errs.address = 'שדה חובה';
      if (!data.area || Number(data.area) <= 0) errs.area = 'שדה חובה';
      if (!data.endDate) errs.endDate = 'שדה חובה';
    }
    if (step === 1) {
      if (!data.clientId && !data.clientName?.trim()) errs.clientId = 'יש לבחור לקוח או להזין שם';
    }
    setErrors(errs);
    return Object.keys(errs).length === 0;
  };

  const nextStep = () => {
    if (!validate()) return;
    setStep(s => s + 1);
  };

  // ── Create project ──
  const createProject = async () => {
    setLoading(true);
    try {
      // Duplicate detection
      try {
        const existing = JSON.parse(localStorage.getItem('ybp_user_projects') || '[]');
        const normName = s => (s || '').trim().toLowerCase().replace(/\s+/g, ' ');
        const match = existing.find(p => normName(p.name) === normName(data.name));
        if (match) {
          const ok = window.confirm(`כבר קיים פרויקט בשם "${match.name}" (${match.id}). האם להמשיך וליצור פרויקט נוסף?`);
          if (!ok) { setLoading(false); return; }
        }
      } catch (_) {}

      const typeObj = PROJECT_TYPES.find(t => t.k === data.type);
      // v3.9.0.43 — שיוך PM אחראי. אם משום מה לא נקבע (משתמש לא מחובר), נופל חזרה למשתמש הנוכחי / 'pm'.
      const pmKey   = data.pmKey || (currentUser ? pmKeyOf(currentUser.email) : 'pm');
      const pmFull  = data.pm    || currentUser?.name || 'מנהל';
      const pmsList = Array.isArray(data.pms) && data.pms.length ? data.pms : [pmKey];
      const newProject = {
        id: 'p_' + Date.now(),
        projectNumber: data.projectNumber,
        name: data.name,
        client: data.clientName || '',
        clientId: data.clientId || null,
        // פרטי לקוח שנמשכו / הוזנו ידנית
        clientContact: data.clientContact || '',
        clientPhone:   data.clientPhone   || '',
        clientEmail:   data.clientEmail   || '',
        // PM (אחראי + רשימה) — נכנסים אוטומטית ל-data jsonb ב-mapProject (לא ב-known list)
        pm:    pmFull,
        pmKey: pmKey,
        pms:   pmsList,
        type: typeObj?.label || data.type,
        cover: data.type,
        address: data.address,
        block: data.block || null,
        parcel: data.parcel || null,
        area: Number(data.area),
        progress: 0,
        status: 'active',
        statusLabel: 'בביצוע',
        budget: Number(data.budget) || 0,
        spent: 0,
        startDate: new Date().toISOString().slice(0, 10),
        endDate: data.endDate,
        daysLeft: Math.round((new Date(data.endDate) - new Date()) / 86400000),
        team: 1,
        openIssues: 0,
        contractorName: data.contractorName || null,
        contractorId: data.contractorId || null,
        contractorPhone: data.contractorPhone || '',
        driveFolderId: '',
        phases: [
          { name: 'תכנון והיתרים', progress: 0, status: 'upcoming' },
          { name: 'הריסה ופינוי',  progress: 0, status: 'upcoming' },
          { name: 'שלד ובנייה',   progress: 0, status: 'upcoming' },
          { name: 'מערכות',       progress: 0, status: 'upcoming' },
          { name: 'גמרים',        progress: 0, status: 'upcoming' },
          { name: 'ריהוט ומסירה', progress: 0, status: 'upcoming' },
          { name: 'מסירה ואכלוס', progress: 0, status: 'upcoming' },
        ],
        createdAt: new Date().toISOString(),
      };

      // הוסף ל-YBP_DATA
      if (window.YBP_DATA) {
        window.YBP_DATA.projects.unshift(newProject);
      }

      // שמור ב-localStorage כדי שישרוד refresh (ימוזג ל-YBP_DATA בטעינה)
      try {
        const userProjects = JSON.parse(localStorage.getItem('ybp_user_projects') || '[]');
        const idx = userProjects.findIndex(p => p.id === newProject.id);
        if (idx !== -1) { userProjects[idx] = newProject; } else { userProjects.unshift(newProject); }
        localStorage.setItem('ybp_user_projects', JSON.stringify(userProjects));
      } catch (e) { console.warn('[NewProjectWizard] localStorage save failed:', e); }

      // שלח Webhook → Make → Drive
      const webhookUrl = getWebhookUrl(NEW_PROJECT_WEBHOOK_KEY);
      if (webhookUrl) {
        try {
          const driveResp = await fetch(webhookUrl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              // snake_case + מפתח אבטחה (תרחיש Make 9037210 דורש את אלה — v3.9.0.42)
              _sk:           '1h4M4SEXbhoYF1YVW1mS6YJZs84yxSVHaBjPDDxMpbak',
              project_id:    newProject.id,
              project_name:  newProject.name,
              // v3.9.0.43 — ה-PM שנבחר ב-wizard (לא המשתמש המחובר), כדי שתיקיית הדרייב תיווצר תחתיו.
              pm_full_name:  newProject.pm,
              pm_name:       newProject.pmKey,
              // camelCase לתאימות לאחור (אינו מזיק)
              projectId: newProject.id,
              projectNumber: newProject.projectNumber,
              projectName: newProject.name,
              projectType: newProject.type,
              address: newProject.address,
              block: newProject.block,
              parcel: newProject.parcel,
              area: newProject.area,
              budget: newProject.budget,
              endDate: newProject.endDate,
              clientName: newProject.client,
              contractorName: newProject.contractorName,
              pmName: newProject.pm,
              createdAt: newProject.createdAt,
              action: 'new_project_setup',
            }),
          });
          if (driveResp.ok) {
            const driveData = await driveResp.json().catch(() => ({}));
            if (driveData.driveFolderId) {
              newProject.driveFolderId = driveData.driveFolderId;
              newProject.driveUrl = driveData.driveUrl || null;
              newProject.driveFolders = driveData.subFolders || null;
              const idx = (window.YBP_DATA?.projects || []).findIndex(p => p.id === newProject.id);
              if (idx !== -1) window.YBP_DATA.projects[idx] = { ...window.YBP_DATA.projects[idx], ...newProject };
              // סנכרן עדכון driveFolderId גם ב-localStorage
              try {
                const userProjects = JSON.parse(localStorage.getItem('ybp_user_projects') || '[]');
                const localIdx = userProjects.findIndex(p => p.id === newProject.id);
                if (localIdx !== -1) { userProjects[localIdx] = { ...userProjects[localIdx], ...newProject }; localStorage.setItem('ybp_user_projects', JSON.stringify(userProjects)); }
              } catch (e) { console.warn('[NewProjectWizard] localStorage update failed:', e); }
            }
          }
        } catch (e) {
          console.warn('[YBP] Webhook failed (non-blocking):', e);
        }
      }

      // שמור את הפרויקט ל-Supabase (מקור-אמת ענן; localStorage נשאר רק כ-cache) — v3.9.0.42
      if (window.saveProjectToSupabase) {
        const res = await window.saveProjectToSupabase(newProject);
        if (!res.ok) {
          console.warn('[NewProjectWizard] Supabase save failed:', res.error);
          if (window.toastError) window.toastError('הפרויקט נוצר מקומית אך לא נשמר בענן — בדוק חיבור');
        }
      }

      // Audit log
      if (window.YBP_AUTH?.addAuditEntry) {
        window.YBP_AUTH.addAuditEntry('create', 'project', newProject.id, `פרויקט חדש: ${newProject.name} (${newProject.projectNumber})`);
      }

      // Toast
      if (window.toastSuccess) window.toastSuccess(`פרויקט "${newProject.name}" נוצר בהצלחה!`);

      // מעבר לחוברת הפרויקט
      onCreated(newProject);

    } catch (e) {
      console.error('[YBP] Create project error:', e);
      if (window.toastError) window.toastError('אירעה שגיאה ביצירת הפרויקט');
    } finally {
      setLoading(false);
    }
  };

  const STEP_TITLES = ['פרטי הפרויקט', 'לקוח וקבלן', 'סיכום ואישור'];

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 9000,
      background: 'rgba(0,0,0,0.5)', backdropFilter: 'blur(4px)',
      display: 'flex', alignItems: 'flex-end',
      fontFamily: 'Assistant, sans-serif', direction: 'rtl',
    }}
      onClick={e => { if (e.target === e.currentTarget) onClose(); }}
    >
      <div style={{
        background: 'var(--ybp-panel,#fff)',
        borderRadius: '20px 20px 0 0',
        width: '100%', maxWidth: 560,
        margin: '0 auto',
        maxHeight: '92vh',
        display: 'flex', flexDirection: 'column',
        boxShadow: '0 -20px 60px rgba(0,0,0,0.25)',
        animation: 'slideUp 0.28s ease',
      }}>

        {/* Header */}
        <div style={{
          padding: '20px 20px 16px',
          borderBottom: `1px solid ${BORDER}`,
          flexShrink: 0,
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 12 }}>
            <div>
              <div style={{ fontSize: 11, color: GOLD, fontWeight: 700, letterSpacing: 1, textTransform: 'uppercase' }}>
                שלב {step + 1} מתוך {STEP_TITLES.length} · {STEP_TITLES[step]}
              </div>
              <h2 style={{ margin: '2px 0 0', fontSize: 20, fontWeight: 800, color: 'var(--ybp-ink,#111827)' }}>
                פרויקט חדש
              </h2>
            </div>
            <button onClick={onClose} style={{
              width: 36, height: 36, borderRadius: 10,
              background: 'var(--ybp-row-hover,#f3f4f6)',
              border: `1px solid ${BORDER}`,
              cursor: 'pointer', fontSize: 18, color: GRAY,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>✕</button>
          </div>
          <StepBar step={step + 1} total={STEP_TITLES.length} />
        </div>

        {/* Content */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '20px 20px 8px' }}>
          {step === 0 && <Step1 data={data} onChange={onChange} errors={errors} profiles={profiles} currentUser={currentUser} isAdmin={isAdmin} />}
          {step === 1 && <Step2 data={data} onChange={onChange} errors={errors} />}
          {step === 2 && <Step3 data={data} />}
        </div>

        {/* Footer */}
        <div style={{
          padding: '16px 20px',
          borderTop: `1px solid ${BORDER}`,
          flexShrink: 0,
          display: 'flex', gap: 10, alignItems: 'center',
        }}>
          {step > 0 ? (
            <button onClick={() => setStep(s => s - 1)} style={{
              padding: '11px 18px', borderRadius: 8,
              background: 'var(--ybp-row-hover,#f3f4f6)',
              border: `1px solid ${BORDER}`,
              fontSize: 14, fontWeight: 600, cursor: 'pointer',
              fontFamily: 'Assistant, sans-serif',
              color: 'var(--ybp-ink,#111827)',
            }}>← חזור</button>
          ) : (
            <button onClick={onClose} style={{
              padding: '11px 18px', borderRadius: 8,
              background: 'var(--ybp-row-hover,#f3f4f6)',
              border: `1px solid ${BORDER}`,
              fontSize: 14, fontWeight: 600, cursor: 'pointer',
              fontFamily: 'Assistant, sans-serif',
              color: 'var(--ybp-ink,#111827)',
            }}>ביטול</button>
          )}

          <button
            onClick={step < STEP_TITLES.length - 1 ? nextStep : createProject}
            disabled={loading}
            style={{
              flex: 1, padding: '12px 18px', borderRadius: 8,
              background: loading ? GRAY : NAVY,
              color: '#fff', border: 'none',
              fontSize: 15, fontWeight: 700, cursor: loading ? 'not-allowed' : 'pointer',
              fontFamily: 'Assistant, sans-serif',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
              transition: 'background 0.15s',
            }}
          >
            {loading ? (
              <>
                <span style={{ fontSize: 16 }}>⏳</span> יוצר פרויקט...
              </>
            ) : step < STEP_TITLES.length - 1 ? (
              <>המשך →</>
            ) : (
              <>🚀 צור פרויקט</>
            )}
          </button>
        </div>

      </div>
    </div>
  );
};

// ── CSS Animation ─────────────────────────────────────────────────────────────
const styleEl = document.createElement('style');
styleEl.textContent = `
  @keyframes slideUp {
    from { transform: translateY(100%); opacity: 0; }
    to   { transform: translateY(0);    opacity: 1; }
  }
`;
document.head.appendChild(styleEl);

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