/**
 * Tenders Module — מכרזים
 * TendersScreen: רשימה + Wizard 4 שלבים + פרטים + השוואת הצעות + בחירת זוכה
 * SyncStore key: ybp_sync_store → tenders[]
 */
(function () {

// ── Constants ─────────────────────────────────────────────────────────────────
const TENDER_STATUSES = {
  draft:    { label: 'טיוטה',        color: '#6b7280', bg: '#f9fafb' },
  active:   { label: 'בהפצה',        color: '#2563eb', bg: '#eff6ff' },
  bidding:  { label: 'בהגשה',        color: '#ea580c', bg: '#fff7ed' },
  review:   { label: 'בבחירה',       color: '#7c3aed', bg: '#f5f3ff' },
  awarded:  { label: 'נבחר זוכה',   color: '#16a34a', bg: '#f0fdf4' },
  cancelled:{ label: 'בוטל',         color: '#dc2626', bg: '#fef2f2' },
};

const BID_STATUSES = {
  pending:  { label: 'בהמתנה',   color: '#eab308', bg: '#fffbeb' },
  winner:   { label: 'זוכה',     color: '#16a34a', bg: '#f0fdf4' },
  lost:     { label: 'לא נבחר', color: '#6b7280', bg: '#f9fafb' },
};

// קטגוריות ממודול ה-Vendors (subset רלוונטי למכרזים)
const TENDER_CATS = [
  'ראשי', 'משנה', 'נירוסטה', 'נגרות', 'מסגרות', 'חדרי קירור',
  'איטום', 'גמר', 'שלט', 'ריצוף', 'גבס',
  'מכשירי מטבח', 'מקררים', 'ברזים', 'מזגנים', 'מנדפים',
  'חשמל', 'אינסטלציה', 'תאורה', 'מיזוג', 'אקוסטיקה',
];

// ── Data helpers ──────────────────────────────────────────────────────────────
function genId() {
  return 'tnd_' + Date.now().toString(36) + Math.random().toString(36).slice(2,6);
}
function loadTenders() {
  return window.SyncStore ? (window.SyncStore.getTenders ? window.SyncStore.getTenders() : []) : [];
}
function saveTenders(list) {
  if (window.SyncStore && window.SyncStore.saveTenders) window.SyncStore.saveTenders(list);
}

// ── StatusBadge helper ────────────────────────────────────────────────────────
const TenderBadge = ({ status }) => {
  const cfg = TENDER_STATUSES[status] || TENDER_STATUSES.draft;
  return (
    <span style={{
      padding: '3px 10px', borderRadius: 99, fontSize: 12, fontWeight: 600,
      background: cfg.bg, color: cfg.color, display: 'inline-block',
    }}>{cfg.label}</span>
  );
};

const BidBadge = ({ status }) => {
  const cfg = BID_STATUSES[status] || BID_STATUSES.pending;
  return (
    <span style={{
      padding: '2px 8px', borderRadius: 99, fontSize: 11, fontWeight: 600,
      background: cfg.bg, color: cfg.color, display: 'inline-block',
    }}>{cfg.label}</span>
  );
};

// ── Shared form primitives (מחוץ לקומפוננטה — למנוע re-mount) ──────────────
const tndInpStyle = {
  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 TndField = ({ 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>
);

// ── TenderAIButton — כפתור AI + פלט מוכלל ─────────────────────────────────
const TenderAIButton = ({ label, prompt, onResult, style: extraStyle }) => {
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(null);

  const run = async () => {
    if (!window.claude) { window.toastError && window.toastError('AI לא זמין'); return; }
    setLoading(true);
    setError(null);
    try {
      const result = await window.claude.complete({
        messages: [{ role: 'user', content: prompt }],
      });
      onResult(result);
    } catch(e) {
      setError('שגיאת AI — נסה שוב');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <button
        onClick={run}
        disabled={loading}
        style={{
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7,
          padding: '9px 16px', borderRadius: 8,
          background: loading ? '#e0e7ff' : 'linear-gradient(135deg,#4f46e5,#7c3aed)',
          color: '#fff', border: 'none', fontSize: 13, fontWeight: 700,
          cursor: loading ? 'not-allowed' : 'pointer',
          fontFamily: 'Assistant, sans-serif',
          transition: 'opacity .15s',
          opacity: loading ? .7 : 1,
          ...extraStyle,
        }}>
        {loading
          ? <><span style={{ animation: 'tnd-spin 1s linear infinite', display: 'inline-block' }}>⟳</span> מעבד...</>
          : <>✦ {label}</>
        }
      </button>
      {error && <span style={{ fontSize: 11, color: '#dc2626' }}>{error}</span>}
      <style>{`@keyframes tnd-spin { to { transform: rotate(360deg); } }`}</style>
    </div>
  );
};

// ── AIResultBox — תיבת תוצאת AI עם copy + apply ───────────────────────────
const AIResultBox = ({ text, onApply, applyLabel = 'השתמש בטקסט', onDismiss }) => {
  const [copied, setCopied] = React.useState(false);
  if (!text) return null;
  return (
    <div style={{
      background: 'linear-gradient(135deg,#faf5ff,#eff6ff)',
      border: '1.5px solid #c4b5fd',
      borderRadius: 10, padding: 14,
      display: 'flex', flexDirection: 'column', gap: 10,
    }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8 }}>
        <span style={{ fontSize: 16, flexShrink: 0, marginTop: 1 }}>✦</span>
        <pre style={{
          margin: 0, flex: 1, fontSize: 13, color: '#1e1b4b',
          lineHeight: 1.65, whiteSpace: 'pre-wrap', fontFamily: 'Assistant, sans-serif',
          direction: 'rtl',
        }}>{text}</pre>
      </div>
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
        {onApply && (
          <button onClick={onApply} style={{
            padding: '7px 14px', borderRadius: 7,
            background: '#4f46e5', color: '#fff',
            border: 'none', fontSize: 13, fontWeight: 700,
            cursor: 'pointer', fontFamily: 'Assistant, sans-serif',
          }}>{applyLabel}</button>
        )}
        <button onClick={() => { navigator.clipboard.writeText(text); setCopied(true); setTimeout(() => setCopied(false), 2000); }} style={{
          padding: '7px 14px', borderRadius: 7,
          background: '#f5f3ff', color: '#4f46e5',
          border: '1px solid #c4b5fd', fontSize: 13, fontWeight: 600,
          cursor: 'pointer', fontFamily: 'Assistant, sans-serif',
        }}>{copied ? '✓ הועתק' : 'העתק'}</button>
        <button onClick={onDismiss} style={{
          padding: '7px 14px', borderRadius: 7,
          background: 'transparent', color: '#9ca3af',
          border: '1px solid #e5e7eb', fontSize: 13,
          cursor: 'pointer', fontFamily: 'Assistant, sans-serif',
        }}>סגור</button>
      </div>
    </div>
  );
};

// ── TenderWizard (4 שלבים) ────────────────────────────────────────────────────
const TenderWizard = ({ projectId, initial, onSave, onCancel }) => {
  const [step, setStep] = React.useState(1);
  const today = new Date().toISOString().slice(0,10);
  const [form, setForm] = React.useState({
    name: '',
    projectId: projectId || '',
    category: '',
    distributeDate: today,
    siteVisitDate: '',
    questionsDeadline: '',
    submissionDeadline: '',
    description: '',
    documents: [],
    invitedVendors: [],
    status: 'draft',
    bids: [],
    ...(initial || {}),
  });
  const [errors, setErrors] = React.useState({});
  const [aiResults, setAiResults] = React.useState({}); // { step1desc, step2recs, step3docs, step4email }
  const setAi = (k, v) => setAiResults(r => ({ ...r, [k]: v }));

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

  // רשימת vendors מ-SyncStore
  const allVendors = React.useMemo(() => {
    const vendors = window.SyncStore ? window.SyncStore.getVendors() : [];
    // פילטר לפי קטגוריה אם נבחרה
    if (form.category) {
      return vendors.filter(v =>
        (v.secondaryCats || []).includes(form.category) ||
        (v.primaryCat === 'קבלן' || v.primaryCat === 'ספק')
      );
    }
    return vendors.filter(v => v.primaryCat === 'קבלן' || v.primaryCat === 'ספק');
  }, [form.category]);

  const toggleVendor = (id) => {
    const curr = form.invitedVendors || [];
    set('invitedVendors', curr.includes(id) ? curr.filter(v => v !== id) : [...curr, id]);
  };

  const autoAssign = () => {
    // שיוך אוטומטי — כל הקבלנים/ספקים בקטגוריה
    const relevant = allVendors.filter(v =>
      !form.category || (v.secondaryCats || []).includes(form.category)
    );
    set('invitedVendors', relevant.map(v => v.id));
    window.toastInfo && window.toastInfo(`שויכו ${relevant.length} בעלי מקצוע`);
  };

  const validateStep = (s) => {
    const e = {};
    if (s === 1) {
      if (!form.name.trim()) e.name = 'שדה חובה';
      if (!form.category) e.category = 'בחר קטגוריה';
      if (!form.submissionDeadline) e.submissionDeadline = 'תאריך חובה';
    }
    if (s === 2) {
      if (!form.invitedVendors || form.invitedVendors.length === 0) e.invitedVendors = 'בחר לפחות קבלן אחד';
    }
    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 = () => {
    onSave({ ...form, status: form.status === 'draft' ? 'active' : form.status });
  };


  const stepLabels = ['פרטי מכרז', 'הזמנת קבלנים', 'מסמכים', 'שליחה'];

  const projects = (window.YBP_DATA || { projects: [] }).projects;

  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: 4, alignItems: 'center' }}>
          {stepLabels.map((l, i) => (
            <React.Fragment key={i}>
              <div title={l} style={{
                width: 26, height: 26, 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: 11, fontWeight: 700, flexShrink: 0, cursor: 'default',
              }}>{step > i+1 ? '✓' : i+1}</div>
              {i < stepLabels.length - 1 && (
                <div style={{ width: 16, height: 2, background: step > i+1 ? '#16a34a' : 'var(--ybp-border,#e5e7eb)', borderRadius: 1 }} />
              )}
            </React.Fragment>
          ))}
        </div>
      </div>

      <div style={{ padding: 20, maxWidth: 560, margin: '0 auto', paddingBottom: 40 }}>
        <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--ybp-ink-soft,#374151)', marginBottom: 16 }}>
          שלב {step}: {stepLabels[step-1]}
        </div>

        {/* ── שלב 1: פרטי מכרז ── */}
        {step === 1 && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <TndField label="שם המכרז" required error={errors.name}>
              <input style={{ ...tndInpStyle, borderColor: errors.name ? '#dc2626' : undefined }}
                value={form.name} onChange={e => set('name', e.target.value)}
                placeholder='מכרז חדרי קירור — מסעדה X' />
            </TndField>

            {!projectId && (
              <TndField label="פרויקט מקושר">
                <select style={{ ...tndInpStyle }} value={form.projectId} onChange={e => set('projectId', e.target.value)}>
                  <option value="">בחר פרויקט...</option>
                  {projects.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
                </select>
              </TndField>
            )}

            <TndField label="קטגוריה" required error={errors.category}>
              <select style={{ ...tndInpStyle, borderColor: errors.category ? '#dc2626' : undefined }}
                value={form.category} onChange={e => set('category', e.target.value)}>
                <option value="">בחר קטגוריה...</option>
                {TENDER_CATS.map(c => <option key={c} value={c}>{c}</option>)}
              </select>
            </TndField>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
              <TndField label="תאריך הפצה">
                <input type="date" style={{ ...tndInpStyle, direction: 'ltr', textAlign: 'right' }}
                  value={form.distributeDate} onChange={e => set('distributeDate', e.target.value)} />
              </TndField>
              <TndField label="סיור קבלנים">
                <input type="date" style={{ ...tndInpStyle, direction: 'ltr', textAlign: 'right' }}
                  value={form.siteVisitDate} onChange={e => set('siteVisitDate', e.target.value)} />
              </TndField>
              <TndField label="אחרון לשאלות">
                <input type="date" style={{ ...tndInpStyle, direction: 'ltr', textAlign: 'right' }}
                  value={form.questionsDeadline} onChange={e => set('questionsDeadline', e.target.value)} />
              </TndField>
              <TndField label="אחרון להגשה" required error={errors.submissionDeadline}>
                <input type="date" style={{ ...tndInpStyle, direction: 'ltr', textAlign: 'right', borderColor: errors.submissionDeadline ? '#dc2626' : undefined }}
                  value={form.submissionDeadline} onChange={e => set('submissionDeadline', e.target.value)} />
              </TndField>
            </div>

            <TndField label="תיאור / הנחיות">
              <textarea style={{ ...tndInpStyle, minHeight: 80, resize: 'vertical' }}
                value={form.description} onChange={e => set('description', e.target.value)}
                placeholder="פירוט דרישות, תנאים מיוחדים..." />
            </TndField>

            {/* AI — יצירת תיאור */}
            <div style={{
              background: 'var(--ybp-panel,#fff)', borderRadius: 10, padding: 14,
              border: '1px solid #e0e7ff', display: 'flex', flexDirection: 'column', gap: 10,
            }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
                <span style={{ fontSize: 13, fontWeight: 700, color: '#4f46e5' }}>✦ עזרת AI</span>
                <TenderAIButton
                  label="צור תיאור מכרז"
                  prompt={`אתה מסייע למנהל פרויקטי בנייה לכתוב מכרז מקצועי בעברית.
שם המכרז: ${form.name || 'מכרז כללי'}
קטגוריה: ${form.category || 'כללי'}
מועד הגשה: ${form.submissionDeadline || 'לא נקבע'}
${form.siteVisitDate ? 'סיור קבלנים: ' + form.siteVisitDate : ''}

כתוב תיאור מכרז מקצועי קצר (3-5 משפטים) שכולל:
1. מה נדרש לבצע (לפי הקטגוריה)
2. דרישות מינימום מהקבלן (ניסיון, רישיון)
3. תנאים מיוחדים רלוונטיים לתחום
כתוב בעברית בלבד, בסגנון עסקי-מקצועי.`}
                  onResult={txt => setAi('step1desc', txt)}
                />
              </div>
              {aiResults.step1desc && (
                <AIResultBox
                  text={aiResults.step1desc}
                  applyLabel="הכנס לשדה תיאור"
                  onApply={() => { set('description', aiResults.step1desc); setAi('step1desc', null); window.toastSuccess && window.toastSuccess('תיאור הוכנס'); }}
                  onDismiss={() => setAi('step1desc', null)}
                />
              )}
            </div>
          </div>
        )}

        {/* ── שלב 2: הזמנת קבלנים ── */}
        {step === 2 && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div style={{ fontSize: 13, color: 'var(--ybp-ink-faint,#6b7280)' }}>
                קטגוריה: <strong>{form.category}</strong> · {allVendors.length} בעלי מקצוע
              </div>
              <button onClick={autoAssign} style={{
                padding: '7px 14px', borderRadius: 8,
                background: '#eff6ff', color: '#2563eb',
                border: '1px solid #bfdbfe', fontSize: 13, fontWeight: 600,
                cursor: 'pointer', fontFamily: 'Assistant, sans-serif',
              }}>⚡ שיוך אוטומטי</button>
            </div>

            {/* AI — המלצת קבלנים */}
            <div style={{
              background: 'var(--ybp-panel,#fff)', borderRadius: 10, padding: 14,
              border: '1px solid #e0e7ff', display: 'flex', flexDirection: 'column', gap: 10,
            }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
                <span style={{ fontSize: 13, fontWeight: 700, color: '#4f46e5' }}>✦ המלצת AI</span>
                <TenderAIButton
                  label="מי מתאים למכרז?"
                  prompt={`אתה יועץ מכרזי בנייה. רשימת בעלי מקצוע הזמינים:
${allVendors.map(v => `- ${v.name}${v.company ? ' (' + v.company + ')' : ''}, דירוג: ${v.rating || 'אין'}/5, קטגוריות: ${(v.secondaryCats||[]).join(', ')}`).join('\n')}

המכרז: "${form.name}", קטגוריה: ${form.category}
${form.description ? 'תיאור: ' + form.description : ''}

המלץ על 3-5 בעלי המקצוע המתאימים ביותר למכרז זה. לכל אחד — שם + סיבה קצרה (משפט אחד).
כתוב בעברית, בסגנון תמציתי.`}
                  onResult={txt => setAi('step2recs', txt)}
                />
              </div>
              {aiResults.step2recs && (
                <AIResultBox
                  text={aiResults.step2recs}
                  onDismiss={() => setAi('step2recs', null)}
                />
              )}
            </div>

            {errors.invitedVendors && (
              <div style={{ padding: '10px 14px', borderRadius: 8, background: '#fef2f2', color: '#dc2626', fontSize: 13 }}>
                {errors.invitedVendors}
              </div>
            )}

            {allVendors.length === 0 ? (
              <EmptyState icon="users" title="אין בעלי מקצוע בקטגוריה זו"
                description="הוסף בעלי מקצוע ב-CRM קודם"
                primaryAction={{ label: 'פתח CRM', onClick: () => {} }} compact />
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {allVendors.map(v => {
                  const sel = (form.invitedVendors || []).includes(v.id);
                  return (
                    <div key={v.id} onClick={() => toggleVendor(v.id)} style={{
                      padding: '12px 16px', borderRadius: 10,
                      background: sel ? '#eff6ff' : 'var(--ybp-panel,#fff)',
                      border: `1.5px solid ${sel ? '#2563eb' : 'var(--ybp-border,#e5e7eb)'}`,
                      cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 12,
                    }}>
                      <div style={{
                        width: 20, height: 20, borderRadius: 4,
                        border: `2px solid ${sel ? '#2563eb' : 'var(--ybp-border,#d1d5db)'}`,
                        background: sel ? '#2563eb' : 'transparent',
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        flexShrink: 0,
                      }}>
                        {sel && <span style={{ color: '#fff', fontSize: 12, lineHeight: 1 }}>✓</span>}
                      </div>
                      <div style={{ flex: 1 }}>
                        <div style={{ fontWeight: 600, fontSize: 14, color: 'var(--ybp-ink,#111827)' }}>{v.name}</div>
                        <div style={{ fontSize: 12, color: 'var(--ybp-ink-faint,#6b7280)' }}>
                          {v.company && `${v.company} · `}{(v.secondaryCats||[]).slice(0,2).join(', ')}
                        </div>
                      </div>
                      {v.rating > 0 && <span style={{ fontSize: 13, color: '#eab308' }}>{'★'.repeat(v.rating)}</span>}
                    </div>
                  );
                })}
              </div>
            )}

            {(form.invitedVendors||[]).length > 0 && (
              <div style={{ fontSize: 13, color: '#16a34a', fontWeight: 600 }}>
                ✓ {form.invitedVendors.length} בעלי מקצוע נבחרו
              </div>
            )}
          </div>
        )}

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

            {/* AI — כתב כמויות + רשימת מסמכים */}
            <div style={{
              background: 'var(--ybp-panel,#fff)', borderRadius: 10, padding: 14,
              border: '1px solid #e0e7ff', display: 'flex', flexDirection: 'column', gap: 10,
            }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, flexWrap: 'wrap' }}>
                <span style={{ fontSize: 13, fontWeight: 700, color: '#4f46e5' }}>✦ AI — מה לכלול?</span>
                <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                  <TenderAIButton
                    label="רשימת מסמכים נדרשים"
                    prompt={`אתה מנהל מכרזי בנייה מנוסה.
מכרז: "${form.name}", קטגוריה: ${form.category}
${form.description ? 'תיאור: ' + form.description : ''}

צור רשימה ממוספרת של המסמכים שיש לצרף למכרז זה.
כלול: תוכניות, מפרטים טכניים, אישורים, ביטוחים, כל מה שרלוונטי לקטגוריה "${form.category}".
רשימה תמציתית, עד 10 פריטים. עברית בלבד.`}
                    onResult={txt => setAi('step3docs', txt)}
                  />
                  <TenderAIButton
                    label="כתב כמויות לדוגמה"
                    prompt={`אתה מהנדס כמויות מנוסה בבנייה.
מכרז: "${form.name}", קטגוריה: ${form.category}
${form.description ? 'תיאור: ' + form.description : ''}

צור כתב כמויות לדוגמה לעבודות ${form.category} בפרויקט בינוי.
פורמט: פריט | תיאור | יחידה | כמות משוערת
כ-8 פריטים טיפוסיים לקטגוריה. עברית בלבד.`}
                    onResult={txt => setAi('step3bill', txt)}
                  />
                </div>
              </div>
              {aiResults.step3docs && (
                <AIResultBox
                  text={aiResults.step3docs}
                  applyLabel="הוסף כהערה במסמך"
                  onApply={() => {
                    set('description', (form.description ? form.description + '\n\n' : '') + 'מסמכים נדרשים:\n' + aiResults.step3docs);
                    setAi('step3docs', null);
                    window.toastSuccess && window.toastSuccess('הרשימה נוספה לתיאור');
                  }}
                  onDismiss={() => setAi('step3docs', null)}
                />
              )}
              {aiResults.step3bill && (
                <AIResultBox
                  text={aiResults.step3bill}
                  applyLabel="הוסף לתיאור"
                  onApply={() => {
                    set('description', (form.description ? form.description + '\n\n' : '') + 'כתב כמויות לדוגמה:\n' + aiResults.step3bill);
                    setAi('step3bill', null);
                    window.toastSuccess && window.toastSuccess('כתב הכמויות נוסף לתיאור');
                  }}
                  onDismiss={() => setAi('step3bill', null)}
                />
              )}
            </div>

            {/* Upload area */}
            <div style={{
              border: '2px dashed var(--ybp-border,#e5e7eb)', borderRadius: 12,
              padding: 32, textAlign: 'center',
              background: 'var(--ybp-row-hover,#f9fafb)', cursor: 'pointer',
            }}
              onClick={() => window.toastInfo && window.toastInfo('העלאת קבצים — יחובר ל-Drive ב-Claude Code')}
            >
              <div style={{ fontSize: 32, marginBottom: 8 }}>📄</div>
              <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ybp-ink,#111827)' }}>לחץ להעלאה</div>
              <div style={{ fontSize: 12, color: 'var(--ybp-ink-faint,#6b7280)', marginTop: 4 }}>PDF, DWG, XLSX — עד 50MB</div>
            </div>

            {/* Existing docs */}
            {(form.documents || []).length > 0 && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {form.documents.map((doc, i) => (
                  <div key={i} style={{
                    padding: '10px 14px', borderRadius: 8,
                    background: 'var(--ybp-panel,#fff)',
                    border: '1px solid var(--ybp-border,#e5e7eb)',
                    display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                  }}>
                    <span style={{ fontSize: 14, color: 'var(--ybp-ink,#111827)' }}>📎 {doc.name}</span>
                    <button onClick={() => set('documents', form.documents.filter((_, j) => j !== i))}
                      style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#dc2626', fontSize: 13 }}>
                      הסר
                    </button>
                  </div>
                ))}
              </div>
            )}

            <div style={{
              padding: '12px 16px', borderRadius: 8,
              background: '#fffbeb', border: '1px solid #fde68a',
              fontSize: 13, color: '#92400e',
            }}>
              💡 ב-Claude Code: העלאה תחובר אוטומטית לתיקיית Drive של הפרויקט
            </div>
          </div>
        )}

        {/* ── שלב 4: שליחה ── */}
        {step === 4 && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
            {/* Summary card */}
            <div style={{
              background: 'var(--ybp-panel,#fff)', borderRadius: 12, padding: 16,
              border: '1px solid var(--ybp-border,#e5e7eb)',
            }}>
              <h3 style={{ margin: '0 0 12px', fontSize: 15, fontWeight: 700, color: 'var(--ybp-ink,#111827)' }}>
                סיכום המכרז
              </h3>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8, fontSize: 14 }}>
                <div><span style={{ color: 'var(--ybp-ink-faint,#6b7280)' }}>שם:</span> <strong>{form.name}</strong></div>
                <div><span style={{ color: 'var(--ybp-ink-faint,#6b7280)' }}>קטגוריה:</span> {form.category}</div>
                <div><span style={{ color: 'var(--ybp-ink-faint,#6b7280)' }}>אחרון להגשה:</span> {form.submissionDeadline}</div>
                <div><span style={{ color: 'var(--ybp-ink-faint,#6b7280)' }}>קבלנים מוזמנים:</span> {(form.invitedVendors||[]).length}</div>
              </div>
            </div>

            {/* AI — ניסוח מייל הזמנה */}
            <div style={{
              background: 'var(--ybp-panel,#fff)', borderRadius: 12, padding: 14,
              border: '1px solid #e0e7ff',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, marginBottom: aiResults.step4email ? 10 : 0 }}>
                <span style={{ fontSize: 13, fontWeight: 700, color: '#4f46e5' }}>✦ AI — ניסוח מייל הזמנה</span>
                <TenderAIButton
                  label="נסח מייל מקצועי"
                  prompt={`אתה מנהל פרויקטים בחברת YBPROJECTS.
כתוב מייל הזמנה מקצועי לקבלנים להגשת הצעת מחיר:

מכרז: ${form.name}
קטגוריה: ${form.category}
${form.description ? 'תיאור: ' + form.description : ''}
${form.siteVisitDate ? 'סיור קבלנים: ' + form.siteVisitDate : ''}
${form.questionsDeadline ? 'אחרון לשאלות: ' + form.questionsDeadline : ''}
מועד אחרון להגשה: ${form.submissionDeadline}

כתוב מייל מלא הכולל: נושא, פתיחה, תיאור קצר של הדרישות, לוחות זמנים, הנחיות הגשה, חתימה.
סגנון: עסקי, מקצועי, ישיר. עברית בלבד.`}
                  onResult={txt => setAi('step4email', txt)}
                />
              </div>
              {aiResults.step4email && (
                <AIResultBox
                  text={aiResults.step4email}
                  applyLabel="פתח ב-Gmail"
                  onApply={() => {
                    const subj = encodeURIComponent(`הזמנה להגשת הצעת מחיר — ${form.name}`);
                    const body = encodeURIComponent(aiResults.step4email);
                    window.open(`https://mail.google.com/mail/?view=cm&fs=1&su=${subj}&body=${body}`, '_blank');
                    window.toastInfo && window.toastInfo('נפתח Gmail עם הטקסט');
                  }}
                  onDismiss={() => setAi('step4email', null)}
                />
              )}
            </div>

            {/* Email preview — ברירת מחדל */}
            {!aiResults.step4email && (
              <div style={{
                background: 'var(--ybp-panel,#fff)', borderRadius: 12, padding: 16,
                border: '1px solid var(--ybp-border,#e5e7eb)',
              }}>
                <h3 style={{ margin: '0 0 8px', fontSize: 14, fontWeight: 700, color: 'var(--ybp-ink,#111827)' }}>
                  📧 תצוגה מקדימה של הזמנה
                </h3>
                <div style={{
                  background: 'var(--ybp-row-hover,#f9fafb)', borderRadius: 8, padding: 12,
                  fontSize: 13, color: 'var(--ybp-ink,#111827)', lineHeight: 1.7,
                  direction: 'rtl',
                }}>
                  <strong>נושא:</strong> הזמנה להגשת הצעת מחיר — {form.name}<br/>
                  <strong>לכבוד:</strong> [שם הקבלן],<br/><br/>
                  אנו מזמינים אתכם להגיש הצעת מחיר עבור: <strong>{form.category}</strong><br/>
                  {form.siteVisitDate && <>סיור קבלנים: <strong>{form.siteVisitDate}</strong><br/></>}
                  מועד אחרון להגשה: <strong>{form.submissionDeadline}</strong><br/><br/>
                  בברכה,<br/>
                  YBPROJECTS
                </div>
              </div>
            )}

            <div style={{ fontSize: 13, color: 'var(--ybp-ink-faint,#6b7280)', padding: '4px 0' }}>
              לחיצה על "שלח מכרז" תשלח מייל ל-{(form.invitedVendors||[]).length} קבלנים ותפעיל את המכרז.
            </div>

            {/* JumboMail */}
            <div style={{
              background: 'var(--ybp-panel,#fff)', borderRadius: 12, padding: 16,
              border: '1px solid var(--ybp-border,#e5e7eb)',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
                <span style={{ fontSize: 22 }}>📦</span>
                <div>
                  <div style={{ fontWeight: 700, fontSize: 14, color: 'var(--ybp-ink,#111827)' }}>JumboMail — שליחת קבצים גדולים</div>
                  <div style={{ fontSize: 12, color: 'var(--ybp-ink-faint,#6b7280)' }}>לקבצים מעל 25MB (תוכניות, כתב כמויות)</div>
                </div>
              </div>
              <button
                onClick={() => {
                  const subject = encodeURIComponent(`מסמכי מכרז: ${form.name}`);
                  const body = encodeURIComponent(`שלום,\n\nמצורפים מסמכי המכרז: ${form.name}\nקטגוריה: ${form.category}\nמועד הגשה: ${form.submissionDeadline}\n\nלינק לקבצים: [יצורף לאחר העלאה ל-JumboMail]\n\nבברכה,\nYBPROJECTS`);
                  window.open(`https://www.jumbomail.me/?subject=${subject}&body=${body}`, '_blank');
                  window.toastInfo && window.toastInfo('נפתח JumboMail — העלה קבצים ושלח');
                }}
                style={{
                  width: '100%', padding: '10px 16px', borderRadius: 8,
                  background: '#eff6ff', color: '#2563eb',
                  border: '1px solid #bfdbfe',
                  fontSize: 14, fontWeight: 600, cursor: 'pointer',
                  fontFamily: 'Assistant, sans-serif',
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                }}>
                📤 פתח JumboMail לשליחת קבצים
              </button>
            </div>
          </div>
        )}

        {/* Navigation */}
        <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 < 4 ? next : handleSubmit} style={{
            flex: 1, padding: 13, borderRadius: 9,
            background: '#1a2c4a', color: '#fff',
            border: 'none', fontSize: 15, fontWeight: 700, cursor: 'pointer',
            fontFamily: 'Assistant, sans-serif',
          }}>
            {step < 4 ? 'הבא ›' : (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>
  );
};

// ── AddBidForm — טופס הוספת הצעה עם העלאת קובץ + AI חילוץ ──────────────────
const bidInpStyle = {
  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)',
  direction: 'rtl', boxSizing: 'border-box',
};

const AddBidForm = ({ tender, vendors, onAdd, onCancel }) => {
  const [bid, setBid] = React.useState({ vendorId: '', vendorName: '', amount: '', paymentTerms: '', duration: '', warranty: '', notes: '' });
  const [extracting, setExtracting] = React.useState(false);
  const [fileName, setFileName] = React.useState(null);
  const [extractError, setExtractError] = React.useState(null);
  const fileRef = React.useRef();

  const setF = (k, v) => setBid(b => ({ ...b, [k]: v }));

  // קריאת קובץ כ-base64
  const readFileAsBase64 = (file) => new Promise((res, rej) => {
    const reader = new FileReader();
    reader.onload = e => res(e.target.result.split(',')[1]);
    reader.onerror = rej;
    reader.readAsDataURL(file);
  });

  const handleFile = async (e) => {
    const file = e.target.files[0];
    if (!file) return;
    setFileName(file.name);
    setExtractError(null);

    // רק טקסט — PDF/תמונה דורשים Vision (Make webhook בייצור)
    // בפרוטוטייפ: שולחים שם הקובץ + טקסט placeholder ל-Claude Haiku
    if (!window.claude) { setExtractError('AI לא זמין'); return; }

    setExtracting(true);
    try {
      // ניסיון לקרוא טקסט (עובד ל-txt, חלקי ל-PDF)
      let fileText = '';
      if (file.type === 'text/plain') {
        fileText = await file.text();
      } else {
        // לקבצים בינאריים — שולחים רק את שם הקובץ ומבקשים מ-AI להדגים חילוץ
        fileText = `[קובץ: ${file.name}, סוג: ${file.type}, גודל: ${(file.size/1024).toFixed(0)}KB]\nבפרוטוטייפ זה, נא הדגם חילוץ שדות מהצעת מחיר בנייה טיפוסית עבור קטגוריה: ${tender.category}`;
      }

      const result = await window.claude.complete({
        messages: [{ role: 'user', content:
          `Extract bid data from this construction quote file and return ONLY a JSON object, no explanation, no markdown, no code blocks.

File: ${file.name}
Context: ${fileText.slice(0, 800)}

Return exactly this JSON (fill in values, use empty string if not found):
{"amount":"number only no currency symbols","paymentTerms":"payment terms text","duration":"number of days only","warranty":"number of months only","notes":"one sentence summary"}` }],
      });

      // פרסור JSON — מחוזק (מטפל גם ב-```json blocks)
      try {
        const cleaned = result.replace(/```(?:json)?/gi, '').trim();
        const jsonMatch = cleaned.match(/\{[\s\S]*\}/);
        if (jsonMatch) {
          const parsed = JSON.parse(jsonMatch[0]);
          // נקה מספרים — הסר כל טקסט שאינו ספרה/נקודה
          const cleanNum = (v) => (v || '').toString().replace(/[^\d.]/g, '');
          const filled = {};
          if (parsed.amount)       filled.amount       = cleanNum(parsed.amount);
          if (parsed.paymentTerms) filled.paymentTerms = parsed.paymentTerms;
          if (parsed.duration)     filled.duration     = cleanNum(parsed.duration);
          if (parsed.warranty)     filled.warranty     = cleanNum(parsed.warranty);
          if (parsed.notes)        filled.notes        = parsed.notes;

          const count = Object.keys(filled).length;
          setBid(b => ({ ...b, ...filled }));
          if (count > 0) {
            window.toastSuccess && window.toastSuccess(`AI חילץ ${count} שדות ✓`);
          } else {
            setExtractError('AI לא מצא נתונים — מלא ידנית');
          }
        } else {
          setExtractError('לא ניתן לחלץ נתונים — מלא ידנית');
        }
      } catch(parseErr) {
        setExtractError('לא ניתן לחלץ נתונים — מלא ידנית');
      }
    } catch(err) {
      setExtractError('שגיאת AI — מלא ידנית');
    } finally {
      setExtracting(false);
    }
  };

  const handleSubmit = () => {
    if (!bid.vendorId || !bid.amount) {
      window.toastError && window.toastError('קבלן וסכום הם שדות חובה');
      return;
    }
    onAdd({ ...bid, id: 'bid_' + Date.now(), status: 'pending' });
    window.toastSuccess && window.toastSuccess('הצעה נוספה');
  };

  return (
    <div style={{
      background: 'var(--ybp-panel,#fff)', borderRadius: 12, padding: 16,
      border: '1.5px solid var(--ybp-border,#e5e7eb)',
      display: 'flex', flexDirection: 'column', gap: 14,
    }}>
      <h4 style={{ margin: 0, fontSize: 15, fontWeight: 700, color: 'var(--ybp-ink,#111827)' }}>הוספת הצעה</h4>

      {/* העלאת קובץ */}
      <div style={{
        border: `2px dashed ${extracting ? '#a5b4fc' : 'var(--ybp-border,#e5e7eb)'}`,
        borderRadius: 10, padding: 16, textAlign: 'center',
        background: extracting ? '#f5f3ff' : fileName ? '#f0fdf4' : 'var(--ybp-row-hover,#f9fafb)',
        cursor: 'pointer', transition: 'all .2s',
        position: 'relative',
      }} onClick={() => !extracting && fileRef.current.click()}>
        <input ref={fileRef} type="file" accept=".pdf,.jpg,.jpeg,.png,.txt,.docx"
          style={{ display: 'none' }} onChange={handleFile} />
        {extracting ? (
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
            <span style={{ fontSize: 28, animation: 'tnd-spin 1s linear infinite', display: 'inline-block' }}>⟳</span>
            <div style={{ fontSize: 13, fontWeight: 700, color: '#4f46e5' }}>AI מחלץ נתונים...</div>
          </div>
        ) : fileName ? (
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
            <span style={{ fontSize: 28 }}>✅</span>
            <div style={{ fontSize: 13, fontWeight: 700, color: '#16a34a' }}>{fileName}</div>
            <div style={{ fontSize: 11, color: '#6b7280' }}>לחץ להחלפה</div>
          </div>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
            <span style={{ fontSize: 28 }}>📎</span>
            <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--ybp-ink,#111827)' }}>העלה קובץ הצעה</div>
            <div style={{ fontSize: 12, color: 'var(--ybp-ink-faint,#6b7280)' }}>PDF, JPG, PNG — AI יחלץ נתונים אוטומטית</div>
          </div>
        )}
      </div>

      {extractError && (
        <div style={{ fontSize: 12, color: '#dc2626', padding: '6px 10px', background: '#fef2f2', borderRadius: 6 }}>
          ⚠️ {extractError}
        </div>
      )}

      {/* בחירת קבלן */}
      <select value={bid.vendorId} onChange={e => setF('vendorId', e.target.value)}
        style={{ ...bidInpStyle, width: '100%' }}>
        <option value="">בחר קבלן... *</option>
        {vendors.filter(v => (tender.invitedVendors||[]).includes(v.id)).map(v => (
          <option key={v.id} value={v.id}>{v.name}</option>
        ))}
        <option value="__other">אחר (הקלד ידנית)</option>
      </select>

      {bid.vendorId === '__other' && (
        <input placeholder="שם הקבלן" value={bid.vendorName}
          onChange={e => setF('vendorName', e.target.value)}
          style={{ ...bidInpStyle, width: '100%' }} />
      )}

      {/* שדות נתונים — ממולאים אוטומטית ע"י AI */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
        <div style={{ position: 'relative' }}>
          <input placeholder="סכום (₪) *" type="number" value={bid.amount}
            onChange={e => setF('amount', e.target.value)}
            style={{ ...bidInpStyle, direction: 'ltr', textAlign: 'right', width: '100%',
              borderColor: bid.amount ? '#16a34a' : undefined }} />
          {bid.amount && <span style={{ position: 'absolute', top: 10, left: 10, fontSize: 12, color: '#16a34a' }}>✦</span>}
        </div>
        <div style={{ position: 'relative' }}>
          <input placeholder="תנאי תשלום" value={bid.paymentTerms}
            onChange={e => setF('paymentTerms', e.target.value)}
            style={{ ...bidInpStyle, width: '100%',
              borderColor: bid.paymentTerms ? '#16a34a' : undefined }} />
          {bid.paymentTerms && <span style={{ position: 'absolute', top: 10, left: 10, fontSize: 12, color: '#16a34a' }}>✦</span>}
        </div>
        <div style={{ position: 'relative' }}>
          <input placeholder="זמן ביצוע (ימים)" type="number" value={bid.duration}
            onChange={e => setF('duration', e.target.value)}
            style={{ ...bidInpStyle, direction: 'ltr', textAlign: 'right', width: '100%',
              borderColor: bid.duration ? '#16a34a' : undefined }} />
          {bid.duration && <span style={{ position: 'absolute', top: 10, left: 10, fontSize: 12, color: '#16a34a' }}>✦</span>}
        </div>
        <div style={{ position: 'relative' }}>
          <input placeholder="אחריות (חודשים)" type="number" value={bid.warranty}
            onChange={e => setF('warranty', e.target.value)}
            style={{ ...bidInpStyle, direction: 'ltr', textAlign: 'right', width: '100%',
              borderColor: bid.warranty ? '#16a34a' : undefined }} />
          {bid.warranty && <span style={{ position: 'absolute', top: 10, left: 10, fontSize: 12, color: '#16a34a' }}>✦</span>}
        </div>
      </div>

      {/* הערות */}
      <input placeholder="הערות נוספות" value={bid.notes}
        onChange={e => setF('notes', e.target.value)}
        style={{ ...bidInpStyle, width: '100%' }} />

      {fileName && (
        <div style={{ fontSize: 11, color: '#6b7280', display: 'flex', alignItems: 'center', gap: 4 }}>
          <span style={{ color: '#16a34a', fontSize: 12 }}>✦</span> שדות מסומנים בירוק חולצו אוטומטית — ניתן לערוך
        </div>
      )}

      <div style={{ display: 'flex', gap: 8 }}>
        <button onClick={handleSubmit} style={{
          flex: 1, padding: '11px', borderRadius: 8, background: '#1a2c4a', color: '#fff',
          border: 'none', fontSize: 14, fontWeight: 700, cursor: 'pointer', fontFamily: 'Assistant, sans-serif',
        }}>הוסף הצעה</button>
        <button onClick={onCancel} style={{
          padding: '11px 18px', borderRadius: 8,
          background: 'var(--ybp-row-hover,#f3f4f6)',
          border: '1px solid var(--ybp-border,#e5e7eb)',
          color: 'var(--ybp-ink,#111827)', fontSize: 14, cursor: 'pointer', fontFamily: 'Assistant, sans-serif',
        }}>ביטול</button>
      </div>
    </div>
  );
};

// ── TenderBidsTable — טבלת השוואת הצעות ──────────────────────────────────────
const TenderBidsTable = ({ tender, vendors, onSelectWinner, onAddBid }) => {
  const [showAddBid, setShowAddBid] = React.useState(false);
  const [aiAnalysis, setAiAnalysis] = React.useState(null);

  const bids = tender.bids || [];
  const minAmount = bids.length > 0 ? Math.min(...bids.map(b => Number(b.amount) || Infinity)) : null;
  const secondMin = bids.length > 1
    ? [...bids].sort((a,b) => Number(a.amount)-Number(b.amount))[1]?.amount
    : null;

  const getVendorName = (id) => {
    const v = vendors.find(x => x.id === id);
    return v ? v.name : id;
  };

  if (bids.length === 0 && !showAddBid) {
    return (
      <EmptyState icon="clipboard" title="אין הצעות עדיין"
        description="הוסף הצעות מחיר שהתקבלו מהקבלנים"
        primaryAction={{ label: '+ הוסף הצעה', onClick: () => setShowAddBid(true) }}
        compact />
    );
  }

  const runAiAnalysis = async () => {
    if (!window.claude) { window.toastError && window.toastError('AI לא זמין'); return; }
    setAiAnalysis('loading');
    try {
      const bidsText = bids.map(b => {
        const vName = getVendorName(b.vendorId);
        return `• ${vName}: ${Number(b.amount).toLocaleString('he-IL')} ₪` +
          (b.paymentTerms ? `, תשלום: ${b.paymentTerms}` : '') +
          (b.duration ? `, זמן: ${b.duration} ימים` : '') +
          (b.warranty ? `, אחריות: ${b.warranty} חודשים` : '');
      }).join('\n');
      const result = await window.claude.complete({
        messages: [{ role: 'user', content:
          `אתה יועץ רכש ומכרזי בנייה מנוסה.
מכרז: "${tender.name}", קטגוריה: ${tender.category}

הצעות שהתקבלו:
${bidsText}

נתח את ההצעות ותן המלצה ברורה:
1. סיכום השוואתי קצר (2-3 משפטים)
2. הזוכה המומלץ שלך + נימוק (מחיר, תנאים, סיכון)
3. נקודות תשומת לב / דגלים אדומים אם יש

כתוב בעברית, תמציתי ומקצועי.` }],
      });
      setAiAnalysis(result);
    } catch(e) {
      setAiAnalysis(null);
      window.toastError && window.toastError('שגיאת AI');
    }
  };

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

      {/* AI ניתוח הצעות */}
      {bids.length >= 2 && (
        <div style={{
          background: 'var(--ybp-panel,#fff)', borderRadius: 10, padding: 14,
          border: '1px solid #e0e7ff', display: 'flex', flexDirection: 'column', gap: 10,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8 }}>
            <span style={{ fontSize: 13, fontWeight: 700, color: '#4f46e5' }}>✦ AI — ניתוח הצעות</span>
            <button
              onClick={runAiAnalysis}
              disabled={aiAnalysis === 'loading'}
              style={{
                display: 'flex', alignItems: 'center', gap: 7,
                padding: '9px 16px', borderRadius: 8,
                background: aiAnalysis === 'loading' ? '#e0e7ff' : 'linear-gradient(135deg,#4f46e5,#7c3aed)',
                color: '#fff', border: 'none', fontSize: 13, fontWeight: 700,
                cursor: aiAnalysis === 'loading' ? 'not-allowed' : 'pointer',
                fontFamily: 'Assistant, sans-serif',
                opacity: aiAnalysis === 'loading' ? .7 : 1,
              }}>
              {aiAnalysis === 'loading'
                ? <><span style={{ animation: 'tnd-spin 1s linear infinite', display: 'inline-block' }}>⟳</span> מנתח...</>
                : <>✦ {aiAnalysis ? 'עדכן ניתוח' : 'נתח הצעות'}</>
              }
            </button>
          </div>
          {aiAnalysis && aiAnalysis !== 'loading' && (
            <AIResultBox
              text={aiAnalysis}
              onDismiss={() => setAiAnalysis(null)}
            />
          )}
        </div>
      )}
      {/* Bids table — cards on mobile */}
      {bids.map(bid => {
        const amt = Number(bid.amount) || 0;
        const isCheapest = amt === minAmount && minAmount !== null;
        const isSecond = String(bid.amount) === String(secondMin);
        return (
          <div key={bid.id} style={{
            background: bid.status === 'winner' ? '#f0fdf4' : 'var(--ybp-panel,#fff)',
            border: `2px solid ${bid.status === 'winner' ? '#16a34a' : isCheapest ? '#fde68a' : 'var(--ybp-border,#e5e7eb)'}`,
            borderRadius: 10, padding: '14px 16px',
            position: 'relative',
          }}>
            {bid.status === 'winner' && (
              <div style={{
                position: 'absolute', top: -1, right: 16,
                background: '#16a34a', color: '#fff',
                fontSize: 11, fontWeight: 700, padding: '2px 10px',
                borderRadius: '0 0 6px 6px',
              }}>🏆 זוכה</div>
            )}
            {isCheapest && bid.status !== 'winner' && (
              <div style={{
                position: 'absolute', top: -1, right: 16,
                background: '#eab308', color: '#fff',
                fontSize: 11, fontWeight: 700, padding: '2px 10px',
                borderRadius: '0 0 6px 6px',
              }}>💰 הזולה ביותר</div>
            )}

            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8, marginTop: bid.status === 'winner' || isCheapest ? 10 : 0 }}>
              <div>
                <div style={{ fontWeight: 700, fontSize: 15, color: 'var(--ybp-ink,#111827)' }}>
                  {getVendorName(bid.vendorId)}
                </div>
                <div style={{ fontSize: 22, fontWeight: 800, color: bid.status === 'winner' ? '#16a34a' : '#1a2c4a', marginTop: 4 }}>
                  {amt > 0 ? amt.toLocaleString('he-IL') + ' ₪' : '—'}
                </div>
              </div>
              <BidBadge status={bid.status} />
            </div>

            <div style={{ display: 'flex', gap: 16, marginTop: 8, flexWrap: 'wrap', fontSize: 12, color: 'var(--ybp-ink-faint,#6b7280)' }}>
              {bid.paymentTerms && <span>💳 {bid.paymentTerms}</span>}
              {bid.duration && <span>⏱ {bid.duration} ימים</span>}
              {bid.warranty && <span>🛡 אחריות {bid.warranty} חודשים</span>}
            </div>

            {bid.status === 'pending' && tender.status !== 'awarded' && (
              <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
                <button onClick={() => onSelectWinner(bid.id)} style={{
                  padding: '7px 14px', borderRadius: 7,
                  background: '#1a2c4a', color: '#fff',
                  border: 'none', fontSize: 13, fontWeight: 600, cursor: 'pointer',
                  fontFamily: 'Assistant, sans-serif',
                }}>🏆 בחר כזוכה</button>
              </div>
            )}
          </div>
        );
      })}

      {/* Add bid form */}
      {showAddBid ? (
        <AddBidForm
          tender={tender}
          vendors={vendors}
          onAdd={(bid) => { onAddBid(bid); setShowAddBid(false); }}
          onCancel={() => setShowAddBid(false)}
        />
      ) : (
        <button onClick={() => setShowAddBid(true)} style={{
          width: '100%', padding: 12, borderRadius: 9,
          background: 'var(--ybp-panel,#fff)',
          border: '1.5px dashed var(--ybp-border,#e5e7eb)',
          color: 'var(--ybp-ink-soft,#374151)',
          fontSize: 14, fontWeight: 600, cursor: 'pointer', fontFamily: 'Assistant, sans-serif',
        }}>+ הוסף הצעה</button>
      )}
    </div>
  );
};

// ── TenderDetail ──────────────────────────────────────────────────────────────
const TenderDetail = ({ tenderId, onBack, onEdit, onUpdate }) => {
  const [tenders, setTenders] = React.useState(loadTenders);
  const [tab, setTab] = React.useState('details'); // details | bids
  const [confirmWinner, setConfirmWinner] = React.useState(null);
  const [confirmCancel, setConfirmCancel] = React.useState(false);

  const tender = tenders.find(t => t.id === tenderId);
  const vendors = window.SyncStore ? window.SyncStore.getVendors() : [];

  if (!tender) return (
    <div style={{ padding: 40, textAlign: 'center', color: 'var(--ybp-ink-faint,#6b7280)', fontFamily: 'Assistant, sans-serif' }}>
      מכרז לא נמצא
    </div>
  );

  const invitedVendors = vendors.filter(v => (tender.invitedVendors || []).includes(v.id));
  const winner = tender.winnerVendorId ? vendors.find(v => v.id === tender.winnerVendorId) : null;
  const winnerBid = winner ? (tender.bids || []).find(b => b.status === 'winner') : null;

  const updateTender = (changes) => {
    const updated = tenders.map(t => t.id === tenderId ? { ...t, ...changes } : t);
    setTenders(updated);
    saveTenders(updated);
    onUpdate && onUpdate();
  };

  const handleSelectWinner = (bidId) => {
    const bid = (tender.bids || []).find(b => b.id === bidId);
    setConfirmWinner(bid);
  };

  const confirmSelectWinner = () => {
    const bid = confirmWinner;
    const updatedBids = (tender.bids || []).map(b => ({
      ...b,
      status: b.id === bid.id ? 'winner' : 'lost',
    }));
    updateTender({
      bids: updatedBids,
      winnerVendorId: bid.vendorId,
      status: 'awarded',
    });
    window.toastSuccess && window.toastSuccess('זוכה נבחר! נשלח עדכון לכל הקבלנים');
    setConfirmWinner(null);
  };

  const handleAddBid = (bid) => {
    updateTender({ bids: [...(tender.bids || []), bid] });
  };

  const getVendorName = (id) => {
    const v = vendors.find(x => x.id === id);
    return v ? v.name : id;
  };

  const tabs = [
    { k: 'details', label: 'פרטים' },
    { k: 'bids', label: `הצעות (${(tender.bids||[]).length})` },
  ];

  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',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
          <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: 17, fontWeight: 700, color: 'var(--ybp-ink,#111827)' }}>{tender.name}</h2>
              <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginTop: 4 }}>
                <TenderBadge status={tender.status} />
                <span style={{ fontSize: 12, color: 'var(--ybp-ink-faint,#6b7280)' }}>{tender.category}</span>
              </div>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            {tender.status !== 'awarded' && tender.status !== 'cancelled' && (
              <button onClick={onEdit} style={{
                padding: '8px 14px', borderRadius: 8, background: '#1a2c4a', color: '#fff',
                border: 'none', fontSize: 13, fontWeight: 600, cursor: 'pointer',
              }}>
                <Icon name="edit" size={14} color="#fff" />
              </button>
            )}
          </div>
        </div>
      </div>

      {/* Winner banner */}
      {tender.status === 'awarded' && winner && winnerBid && (
        <div style={{
          background: '#f0fdf4', borderBottom: '1px solid #bbf7d0',
          padding: '12px 20px', display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <span style={{ fontSize: 24 }}>🏆</span>
          <div>
            <div style={{ fontWeight: 700, fontSize: 14, color: '#16a34a' }}>
              זוכה: {winner.name}
            </div>
            <div style={{ fontSize: 13, color: '#15803d' }}>
              סכום: {Number(winnerBid.amount).toLocaleString('he-IL')} ₪
            </div>
          </div>
        </div>
      )}

      {/* Tabs */}
      <div style={{
        background: 'var(--ybp-panel,#fff)',
        borderBottom: '1px solid var(--ybp-border,#e5e7eb)',
        display: 'flex', padding: '0 20px',
      }}>
        {tabs.map(t => (
          <button key={t.k} onClick={() => setTab(t.k)} style={{
            padding: '10px 16px', background: 'none', border: 'none', cursor: 'pointer',
            fontSize: 14, fontWeight: tab === t.k ? 700 : 500,
            color: tab === t.k ? '#1a2c4a' : 'var(--ybp-ink-faint,#6b7280)',
            borderBottom: tab === t.k ? '2.5px solid #1a2c4a' : '2.5px solid transparent',
            fontFamily: 'Assistant, sans-serif',
          }}>{t.label}</button>
        ))}
      </div>

      <div style={{ padding: 16, maxWidth: 600, margin: '0 auto' }}>
        {/* Details tab */}
        {tab === 'details' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
            {/* Dates */}
            <div style={{ background: 'var(--ybp-panel,#fff)', borderRadius: 12, padding: 16, border: '1px solid var(--ybp-border,#e5e7eb)' }}>
              <h3 style={{ margin: '0 0 12px', fontSize: 14, fontWeight: 700, color: 'var(--ybp-ink,#111827)' }}>לוחות זמנים</h3>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                {[
                  ['📤 הפצה', tender.distributeDate],
                  ['🏗 סיור קבלנים', tender.siteVisitDate],
                  ['❓ אחרון לשאלות', tender.questionsDeadline],
                  ['📬 אחרון להגשה', tender.submissionDeadline],
                ].map(([label, date]) => date ? (
                  <div key={label} style={{
                    padding: '10px 12px', borderRadius: 8,
                    background: 'var(--ybp-row-hover,#f6f7f9)',
                  }}>
                    <div style={{ fontSize: 11, color: 'var(--ybp-ink-faint,#6b7280)', marginBottom: 3 }}>{label}</div>
                    <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ybp-ink,#111827)' }}>{date}</div>
                  </div>
                ) : null)}
              </div>
            </div>

            {/* Description */}
            {tender.description && (
              <div style={{ background: 'var(--ybp-panel,#fff)', borderRadius: 12, padding: 16, border: '1px solid var(--ybp-border,#e5e7eb)' }}>
                <h3 style={{ margin: '0 0 8px', fontSize: 14, fontWeight: 700, color: 'var(--ybp-ink,#111827)' }}>תיאור</h3>
                <p style={{ margin: 0, fontSize: 14, color: 'var(--ybp-ink,#111827)', lineHeight: 1.6 }}>{tender.description}</p>
              </div>
            )}

            {/* Invited vendors */}
            <div style={{ background: 'var(--ybp-panel,#fff)', borderRadius: 12, padding: 16, border: '1px solid var(--ybp-border,#e5e7eb)' }}>
              <h3 style={{ margin: '0 0 12px', fontSize: 14, fontWeight: 700, color: 'var(--ybp-ink,#111827)' }}>
                קבלנים מוזמנים ({invitedVendors.length})
              </h3>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {invitedVendors.map(v => (
                  <div key={v.id} style={{
                    display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                    padding: '8px 12px', borderRadius: 8,
                    background: v.id === tender.winnerVendorId ? '#f0fdf4' : 'var(--ybp-row-hover,#f6f7f9)',
                  }}>
                    <div style={{ fontWeight: 600, fontSize: 14, color: 'var(--ybp-ink,#111827)' }}>
                      {v.id === tender.winnerVendorId && '🏆 '}{v.name}
                    </div>
                    <div style={{ fontSize: 12, color: 'var(--ybp-ink-faint,#6b7280)' }}>{v.phone}</div>
                  </div>
                ))}
              </div>
            </div>

            {/* Status actions */}
            {tender.status !== 'awarded' && tender.status !== 'cancelled' && (
              <div style={{ display: 'flex', gap: 8 }}>
                {tender.status === 'draft' && (
                  <button onClick={() => { updateTender({ status: 'active' }); window.toastSuccess && window.toastSuccess('המכרז הופץ'); }} style={{
                    flex: 1, padding: 12, borderRadius: 8, background: '#2563eb', color: '#fff',
                    border: 'none', fontSize: 14, fontWeight: 600, cursor: 'pointer', fontFamily: 'Assistant, sans-serif',
                  }}>📤 הפץ מכרז</button>
                )}
                <button onClick={() => setConfirmCancel(true)} style={{
                  padding: '12px 16px', borderRadius: 8,
                  background: '#fef2f2', color: '#dc2626',
                  border: '1px solid #fecaca', fontSize: 14, fontWeight: 600, cursor: 'pointer', fontFamily: 'Assistant, sans-serif',
                }}>בטל מכרז</button>
              </div>
            )}
          </div>
        )}

        {/* Bids tab */}
        {tab === 'bids' && (
          <TenderBidsTable
            tender={tender}
            vendors={vendors}
            onSelectWinner={handleSelectWinner}
            onAddBid={handleAddBid}
          />
        )}
      </div>

      {/* Confirm winner dialog */}
      {confirmWinner && (
        <ConfirmDialog isOpen
          title="בחר זוכה במכרז?"
          description={`קבלן: ${getVendorName(confirmWinner.vendorId)}\nסכום: ${Number(confirmWinner.amount).toLocaleString('he-IL')} ₪\n\nהפעולה תשלח עדכון לכל הקבלנים האחרים.`}
          confirmLabel="אשר זוכה"
          onConfirm={confirmSelectWinner}
          onCancel={() => setConfirmWinner(null)}
        />
      )}

      {confirmCancel && (
        <ConfirmDialog isOpen
          title="בטל מכרז?"
          description="תישלח הודעת ביטול לכל הקבלנים המוזמנים."
          confirmLabel="בטל מכרז"
          confirmVariant="danger"
          onConfirm={() => {
            updateTender({ status: 'cancelled' });
            window.toastSuccess && window.toastSuccess('המכרז בוטל');
            setConfirmCancel(false);
          }}
          onCancel={() => setConfirmCancel(false)}
        />
      )}
    </div>
  );
};

// ── TendersScreen (main) ──────────────────────────────────────────────────────
const TendersScreen = ({ projectId, onBack }) => {
  const [tenders, setTenders] = React.useState(loadTenders);
  const [view, setView] = React.useState('list'); // list | wizard | detail
  const [selectedId, setSelectedId] = React.useState(null);
  const [editTender, setEditTender] = React.useState(null);
  const [filterStatus, setFilterStatus] = React.useState('all');
  const [search, setSearch] = React.useState('');
  const [confirmDelete, setConfirmDelete] = React.useState(null);

  // פילטר לפי פרויקט אם הועבר projectId
  const projectTenders = projectId
    ? tenders.filter(t => t.projectId === projectId)
    : tenders;

  const filtered = projectTenders.filter(t => {
    const matchStatus = filterStatus === 'all' || t.status === filterStatus;
    const matchSearch = !search || t.name.includes(search) || t.category.includes(search);
    return matchStatus && matchSearch;
  });

  const persist = (list) => { setTenders(list); saveTenders(list); };

  const handleSave = (form) => {
    if (editTender && editTender.id) {
      persist(tenders.map(t => t.id === editTender.id ? { ...t, ...form } : t));
      window.toastSuccess && window.toastSuccess('מכרז עודכן');
    } else {
      const newT = { ...form, id: genId(), createdAt: new Date().toLocaleDateString('he-IL'), bids: [] };
      persist([newT, ...tenders]);
      window.toastSuccess && window.toastSuccess('מכרז נוצר ונשלח לקבלנים 🚀');
    }
    setView('list'); setEditTender(null);
  };

  const handleDelete = (id) => {
    persist(tenders.filter(t => t.id !== id));
    window.toastSuccess && window.toastSuccess('מכרז נמחק');
    setView('list'); setConfirmDelete(null);
  };

  // ── Wizard view ──
  if (view === 'wizard') {
    return (
      <TenderWizard
        projectId={projectId}
        initial={editTender}
        onSave={handleSave}
        onCancel={() => { setView(editTender ? 'detail' : 'list'); setEditTender(null); }}
      />
    );
  }

  // ── Detail view ──
  if (view === 'detail' && selectedId) {
    return (
      <div style={{ minHeight: '100vh', background: 'var(--ybp-bg,#f6f7f9)' }}>
        <TenderDetail
          tenderId={selectedId}
          onBack={() => setView('list')}
          onEdit={() => { setEditTender(tenders.find(t => t.id === selectedId)); setView('wizard'); }}
          onUpdate={() => setTenders(loadTenders())}
        />
        <div style={{ padding: '0 16px 32px', maxWidth: 600, 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 statusCounts = { all: projectTenders.length };
  Object.keys(TENDER_STATUSES).forEach(s => {
    statusCounts[s] = projectTenders.filter(t => t.status === s).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)' }}>
              {projectTenders.filter(t => t.status === 'active' || t.status === 'bidding').length} פעילים
            </div>
          </div>
        </div>
        <button onClick={() => { setEditTender(null); setView('wizard'); }} 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' }}>
        <input value={search} onChange={e => setSearch(e.target.value)}
          placeholder="חיפוש לפי שם, קטגוריה..."
          style={{
            width: '100%', padding: '10px 14px', 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>

      {/* Status filter chips */}
      <div style={{ padding: '10px 16px 0', display: 'flex', gap: 6, overflowX: 'auto' }}>
        {[['all', 'הכל'], ...Object.entries(TENDER_STATUSES).map(([k, v]) => [k, v.label])].map(([k, label]) => (
          <button key={k} onClick={() => setFilterStatus(k)} style={{
            padding: '6px 12px', borderRadius: 99, whiteSpace: 'nowrap',
            background: filterStatus === k ? '#1a2c4a' : 'var(--ybp-panel,#fff)',
            color: filterStatus === k ? '#fff' : 'var(--ybp-ink-soft,#374151)',
            border: '1.5px solid ' + (filterStatus === k ? '#1a2c4a' : 'var(--ybp-border,#e5e7eb)'),
            fontSize: 12, fontWeight: filterStatus === k ? 700 : 500, cursor: 'pointer',
            fontFamily: 'Assistant, sans-serif', flexShrink: 0,
          }}>
            {label} {statusCounts[k] !== undefined ? `(${statusCounts[k]})` : ''}
          </button>
        ))}
      </div>

      {/* Tender cards */}
      <div style={{ padding: '12px 16px 32px' }}>
        {filtered.length === 0 ? (
          <EmptyState
            icon="clipboard"
            title={search || filterStatus !== 'all' ? 'לא נמצאו מכרזים' : 'אין מכרזים עדיין'}
            description={search || filterStatus !== 'all' ? 'נסה לנקות פילטרים' : 'פתח מכרז כדי להזמין קבלנים'}
            primaryAction={
              search || filterStatus !== 'all'
                ? { label: 'נקה פילטרים', onClick: () => { setSearch(''); setFilterStatus('all'); } }
                : { label: '+ מכרז חדש', onClick: () => setView('wizard') }
            }
          />
        ) : (
          filtered.map(t => {
            const cfg = TENDER_STATUSES[t.status] || TENDER_STATUSES.draft;
            const bids = t.bids || [];
            const winner = t.winnerVendorId
              ? (window.SyncStore ? window.SyncStore.getVendors() : []).find(v => v.id === t.winnerVendorId)
              : null;
            const winnerBid = winner ? bids.find(b => b.status === 'winner') : null;

            return (
              <div key={t.id}
                onClick={() => { setSelectedId(t.id); setView('detail'); }}
                style={{
                  background: 'var(--ybp-panel,#fff)', borderRadius: 12, padding: 16,
                  marginBottom: 12, border: '1px solid var(--ybp-border,#e5e7eb)',
                  cursor: 'pointer',
                }}
                onMouseEnter={e => e.currentTarget.style.boxShadow = '0 4px 12px rgba(0,0,0,0.08)'}
                onMouseLeave={e => e.currentTarget.style.boxShadow = 'none'}
              >
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8 }}>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 700, fontSize: 15, color: 'var(--ybp-ink,#111827)', marginBottom: 4 }}>{t.name}</div>
                    <div style={{ fontSize: 12, color: 'var(--ybp-ink-faint,#6b7280)', marginBottom: 8 }}>
                      {t.category} · {(t.invitedVendors||[]).length} קבלנים
                    </div>
                  </div>
                  <TenderBadge status={t.status} />
                </div>

                {/* Winner banner */}
                {winner && winnerBid && (
                  <div style={{
                    background: '#f0fdf4', borderRadius: 8, padding: '8px 12px',
                    display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                    marginBottom: 8,
                  }}>
                    <span style={{ fontSize: 13, fontWeight: 600, color: '#16a34a' }}>🏆 {winner.name}</span>
                    <span style={{ fontSize: 13, fontWeight: 700, color: '#15803d' }}>
                      {Number(winnerBid.amount).toLocaleString('he-IL')} ₪
                    </span>
                  </div>
                )}

                <div style={{ display: 'flex', gap: 16, fontSize: 12, color: 'var(--ybp-ink-faint,#6b7280)' }}>
                  {t.submissionDeadline && <span>📬 {t.submissionDeadline}</span>}
                  {bids.length > 0 && <span>📋 {bids.length} הצעות</span>}
                </div>
              </div>
            );
          })
        )}
      </div>
    </div>
  );
};

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