/**
 * Plans Distribution Module — הפצת תוכניות
 * PlansDistributionModal: בחירת יועצים + preview מייל + שליחה
 * משלים את plans.jsx הקיים
 * SyncStore: vendors (יועצים) + plans distribution log
 */
(function () {

const { useState, useMemo } = React;

// ── Constants ──────────────────────────────────────────────────────────────────
const PLAN_TYPES = {
  consultants: { label: 'יועצים',         icon: '👔', vendorCats: ['יועץ'] },
  kitchen:     { label: 'מטבח',           icon: '🍽', vendorCats: ['מטבח', 'נירוסטה'] },
  arch:        { label: 'אדריכל-מעצב',   icon: '🏛', vendorCats: ['אדריכל', 'מעצב', 'קבלן ראשי'] },
  contractor:  { label: 'קבלן ראשי',     icon: '🏗', vendorCats: ['ראשי', 'משנה'] },
};

// ── Helper: build Gmail compose URL ──────────────────────────────────────────
function buildGmailUrl({ to, subject, body }) {
  const params = new URLSearchParams();
  if (to && to.length) params.append('to', to.join(','));
  params.append('su', subject || '');
  params.append('body', body || '');
  return `https://mail.google.com/mail/?view=cm&fs=1&${params.toString()}`;
}

// ── Distribution history store ─────────────────────────────────────────────
function getDistHistory(projectId) {
  return window.cloudLoadSync ? window.cloudLoadSync(`dist_history_${projectId}`, []) : [];
}
function saveDistHistory(projectId, list) {
  if (window.cloudSaveSync) window.cloudSaveSync(`dist_history_${projectId}`, list);
}

// ── PlansDistributionModal ─────────────────────────────────────────────────
const PlansDistributionModal = ({ projectId, planName, planType, onClose }) => {
  const vendors = window.SyncStore ? window.SyncStore.getVendors() : [];
  const projects = window.YBP_DATA ? window.YBP_DATA.projects : [];
  const project = projects.find(p => p.id === projectId) || projects[0];

  // Relevant vendors by plan type
  const relevantVendors = useMemo(() => {
    if (!planType || !PLAN_TYPES[planType]) return vendors.filter(v => v.active);
    const cats = PLAN_TYPES[planType].vendorCats;
    return vendors.filter(v =>
      v.active && (
        cats.includes(v.primaryCat) ||
        (v.secondaryCats || []).some(c => cats.includes(c))
      )
    );
  }, [planType, vendors]);

  const [selected, setSelected] = useState(
    relevantVendors.map(v => v.id) // ברירת מחדל — כולם מסומנים
  );
  const [subject, setSubject] = useState(
    `תוכנית מעודכנת: ${planName || 'תוכנית'} — פרויקט ${project?.name || ''}`
  );
  const [note, setNote] = useState('');
  const [sending, setSending] = useState(false);
  const [sent, setSent] = useState(false);

  const toggleVendor = (id) => {
    setSelected(s => s.includes(id) ? s.filter(x => x !== id) : [...s, id]);
  };

  const selectedVendors = vendors.filter(v => selected.includes(v.id));
  const toEmails = selectedVendors.map(v => v.email).filter(Boolean);

  const emailBody = `שלום,

מצורפת תוכנית מעודכנת לעיונכם:
📐 ${planName || 'תוכנית'}
🏗 פרויקט: ${project?.name || ''}
📍 כתובת: ${project?.location || project?.address || ''}

${note ? `הערות:\n${note}\n` : ''}
הקובץ נמצא בתיקיית Drive של הפרויקט.

לשאלות ניתן לפנות ישירות.

בברכה,
${project?.pm || 'מנהל הפרויקט'}
YBPROJECTS`;

  const handleSend = () => {
    if (toEmails.length === 0) {
      window.toastError && window.toastError('אין כתובות מייל לנבחרים');
      return;
    }
    setSending(true);

    // שמור לוג הפצה
    const history = getDistHistory(projectId);
    history.unshift({
      id: 'dist_' + Date.now(),
      planName,
      planType,
      recipients: selectedVendors.map(v => ({ id: v.id, name: v.name, email: v.email })),
      subject,
      sentAt: new Date().toISOString(),
      sentBy: window.YBP_AUTH?.getSession()?.name || 'מנהל',
    });
    saveDistHistory(projectId, history.slice(0, 50));

    // פתח Gmail
    const gmailUrl = buildGmailUrl({ to: toEmails, subject, body: emailBody });
    window.open(gmailUrl, '_blank');

    // הצג הצלחה
    setTimeout(() => {
      setSending(false);
      setSent(true);
      window.toastSuccess && window.toastSuccess(`📧 נשלח ל-${toEmails.length} נמענים`);
    }, 600);
  };

  const handleJumboMail = () => {
    window.open('https://www.jumbomail.me/', '_blank');
    window.toastInfo && window.toastInfo('JumboMail נפתח — העלה את הקובץ ושלח לנמענים');
  };

  const inpStyle = {
    width: '100%', padding: '9px 12px', borderRadius: 8,
    border: '1.5px solid var(--ybp-border,#e5e7eb)',
    fontSize: 14, fontFamily: 'Assistant, sans-serif',
    background: 'var(--ybp-input-bg,#fff)', color: 'var(--ybp-ink,#111827)',
    outline: 'none', boxSizing: 'border-box', direction: 'rtl',
  };

  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)',
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
      zIndex: 9000, fontFamily: 'Assistant, sans-serif', direction: 'rtl',
    }} onClick={e => e.target === e.currentTarget && onClose()}>
      <div style={{
        background: 'var(--ybp-panel,#fff)',
        borderRadius: '16px 16px 0 0',
        width: '100%', maxWidth: 560,
        maxHeight: '90vh', overflowY: 'auto',
        padding: '0 0 40px',
      }}>
        {/* Handle */}
        <div style={{ display: 'flex', justifyContent: 'center', padding: '12px 0 0' }}>
          <div style={{ width: 36, height: 4, borderRadius: 2, background: 'var(--ybp-border,#e5e7eb)' }} />
        </div>

        {/* Header */}
        <div style={{
          padding: '12px 20px 14px',
          borderBottom: '1px solid var(--ybp-border,#e5e7eb)',
          display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start',
        }}>
          <div>
            <h3 style={{ margin: 0, fontSize: 17, fontWeight: 700, color: 'var(--ybp-ink,#111827)' }}>
              📤 עדכן יועצים
            </h3>
            <div style={{ fontSize: 12, color: 'var(--ybp-ink-faint,#6b7280)', marginTop: 3 }}>
              {planName} · {project?.name}
            </div>
          </div>
          <button onClick={onClose} style={{
            background: 'none', border: 'none', cursor: 'pointer',
            fontSize: 20, color: 'var(--ybp-ink-faint,#6b7280)', padding: 4,
          }}>✕</button>
        </div>

        <div style={{ padding: '16px 20px', display: 'flex', flexDirection: 'column', gap: 16 }}>

          {/* נמענים */}
          <div>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
              <label style={{ fontSize: 12, fontWeight: 700, color: 'var(--ybp-ink-soft,#374151)', letterSpacing: 0.3, textTransform: 'uppercase' }}>
                נמענים ({selected.length})
              </label>
              <div style={{ display: 'flex', gap: 8 }}>
                <button onClick={() => setSelected(vendors.map(v => v.id))} style={{
                  fontSize: 11, color: '#2563eb', background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'Assistant, sans-serif',
                }}>בחר הכל</button>
                <button onClick={() => setSelected([])} style={{
                  fontSize: 11, color: '#6b7280', background: 'none', border: 'none', cursor: 'pointer', fontFamily: 'Assistant, sans-serif',
                }}>נקה</button>
              </div>
            </div>

            {relevantVendors.length === 0 ? (
              <div style={{
                padding: '14px', borderRadius: 8, background: '#fffbeb',
                border: '1px solid #fde68a', fontSize: 13, color: '#92400e', textAlign: 'center',
              }}>
                אין יועצים/קבלנים מוגדרים ב-CRM — הוסף בעלי מקצוע קודם
              </div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6, maxHeight: 240, overflowY: 'auto' }}>
                {vendors.filter(v => v.active).map(v => {
                  const sel = selected.includes(v.id);
                  const isRelevant = relevantVendors.some(r => r.id === v.id);
                  return (
                    <div key={v.id} onClick={() => toggleVendor(v.id)} style={{
                      padding: '10px 12px', borderRadius: 9,
                      background: sel ? '#eff6ff' : 'var(--ybp-row-hover,#f9fafb)',
                      border: `1.5px solid ${sel ? '#2563eb' : 'transparent'}`,
                      cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 10,
                    }}>
                      <div style={{
                        width: 18, height: 18, 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: 11 }}>✓</span>}
                      </div>
                      <div style={{ flex: 1 }}>
                        <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--ybp-ink,#111827)', display: 'flex', gap: 6, alignItems: 'center' }}>
                          {v.name}
                          {isRelevant && (
                            <span style={{ fontSize: 10, padding: '1px 6px', borderRadius: 99, background: '#dbeafe', color: '#1d4ed8', fontWeight: 700 }}>
                              רלוונטי
                            </span>
                          )}
                        </div>
                        <div style={{ fontSize: 11, color: 'var(--ybp-ink-faint,#6b7280)' }}>
                          {v.email || 'אין מייל'} · {v.primaryCat}
                        </div>
                      </div>
                    </div>
                  );
                })}
              </div>
            )}
          </div>

          {/* נושא מייל */}
          <div>
            <label style={{ fontSize: 12, fontWeight: 700, color: 'var(--ybp-ink-soft,#374151)', letterSpacing: 0.3, textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>
              נושא המייל
            </label>
            <input style={inpStyle} value={subject} onChange={e => setSubject(e.target.value)} />
          </div>

          {/* הערות */}
          <div>
            <label style={{ fontSize: 12, fontWeight: 700, color: 'var(--ybp-ink-soft,#374151)', letterSpacing: 0.3, textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>
              הערות (אופציונלי)
            </label>
            <textarea
              style={{ ...inpStyle, minHeight: 70, resize: 'vertical' }}
              value={note}
              onChange={e => setNote(e.target.value)}
              placeholder="הערות מיוחדות לגרסה זו..." />
          </div>

          {/* Preview */}
          <div style={{
            background: 'var(--ybp-row-hover,#f9fafb)', borderRadius: 8, padding: 12,
            border: '1px solid var(--ybp-border,#e5e7eb)', fontSize: 12,
            color: 'var(--ybp-ink,#111827)', lineHeight: 1.8,
            maxHeight: 140, overflowY: 'auto',
            whiteSpace: 'pre-wrap', direction: 'rtl',
          }}>
            {emailBody}
          </div>

          {/* כפתורי שליחה */}
          {sent ? (
            <div style={{
              padding: '14px', borderRadius: 10,
              background: '#f0fdf4', border: '1px solid #bbf7d0',
              textAlign: 'center', fontSize: 15, fontWeight: 700, color: '#16a34a',
            }}>
              ✅ נשלח ל-{toEmails.length} נמענים!
            </div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {/* Gmail */}
              <button onClick={handleSend} disabled={sending || toEmails.length === 0} style={{
                width: '100%', padding: '13px', borderRadius: 9,
                background: toEmails.length === 0 ? '#e5e7eb' : '#1a2c4a',
                color: '#fff', border: 'none',
                fontSize: 15, fontWeight: 700, cursor: toEmails.length === 0 ? 'not-allowed' : 'pointer',
                fontFamily: 'Assistant, sans-serif',
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                opacity: sending ? 0.7 : 1,
              }}>
                {sending ? '⏳ שולח...' : `📧 שלח ב-Gmail (${toEmails.length} נמענים)`}
              </button>

              {/* JumboMail לקבצים גדולים */}
              <button onClick={handleJumboMail} style={{
                width: '100%', padding: '11px', borderRadius: 9,
                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 style={{ fontSize: 11, color: 'var(--ybp-ink-faint,#9ca3af)', textAlign: 'center' }}>
                JumboMail מתאים לקבצי PDF/DWG מעל 25MB
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

// ── DistributionHistoryPanel ─────────────────────────────────────────────────
const DistributionHistoryPanel = ({ projectId, onClose }) => {
  const history = getDistHistory(projectId);

  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)',
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
      zIndex: 9000, fontFamily: 'Assistant, sans-serif', direction: 'rtl',
    }} onClick={e => e.target === e.currentTarget && onClose()}>
      <div style={{
        background: 'var(--ybp-panel,#fff)',
        borderRadius: '16px 16px 0 0',
        width: '100%', maxWidth: 560,
        maxHeight: '70vh', overflowY: 'auto',
        padding: '0 0 40px',
      }}>
        <div style={{ display: 'flex', justifyContent: 'center', padding: '12px 0 0' }}>
          <div style={{ width: 36, height: 4, borderRadius: 2, background: 'var(--ybp-border,#e5e7eb)' }} />
        </div>
        <div style={{ padding: '12px 20px 14px', borderBottom: '1px solid var(--ybp-border,#e5e7eb)', display: 'flex', justifyContent: 'space-between' }}>
          <h3 style={{ margin: 0, fontSize: 16, fontWeight: 700, color: 'var(--ybp-ink,#111827)' }}>היסטוריית הפצות</h3>
          <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 20, color: 'var(--ybp-ink-faint,#6b7280)' }}>✕</button>
        </div>
        <div style={{ padding: '12px 20px' }}>
          {history.length === 0 ? (
            <div style={{ textAlign: 'center', color: 'var(--ybp-ink-faint,#6b7280)', padding: '24px 0', fontSize: 14 }}>
              אין היסטוריית הפצות עדיין
            </div>
          ) : history.map((h, i) => (
            <div key={i} style={{
              padding: '12px 0',
              borderBottom: i < history.length - 1 ? '1px solid var(--ybp-border,#e5e7eb)' : 'none',
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                <div style={{ fontWeight: 700, fontSize: 14, color: 'var(--ybp-ink,#111827)' }}>{h.planName}</div>
                <div style={{ fontSize: 11, color: 'var(--ybp-ink-faint,#6b7280)' }}>
                  {new Date(h.sentAt).toLocaleDateString('he-IL', { day:'2-digit', month:'2-digit', hour:'2-digit', minute:'2-digit' })}
                </div>
              </div>
              <div style={{ fontSize: 12, color: 'var(--ybp-ink-faint,#6b7280)', marginTop: 4 }}>
                נשלח ל-{h.recipients?.length || 0} נמענים · {h.sentBy}
              </div>
              <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap', marginTop: 6 }}>
                {(h.recipients || []).map((r, j) => (
                  <span key={j} style={{
                    padding: '2px 8px', borderRadius: 99, fontSize: 11,
                    background: 'var(--ybp-row-hover,#f3f4f6)', color: 'var(--ybp-ink-soft,#374151)',
                  }}>{r.name}</span>
                ))}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

// ── DistributeButton — כפתור שמשתלב ב-plans.jsx ────────────────────────────
const DistributeButton = ({ projectId, planName, planType, daysSinceDistribution }) => {
  const [showModal, setShowModal] = useState(false);
  const [showHistory, setShowHistory] = useState(false);

  const isOverdue = daysSinceDistribution >= 7;

  return (
    <>
      <div style={{ display: 'flex', gap: 6 }}>
        <button onClick={() => setShowModal(true)} style={{
          display: 'flex', alignItems: 'center', gap: 5,
          padding: '7px 12px', borderRadius: 7,
          background: isOverdue ? '#fff7ed' : '#eff6ff',
          color: isOverdue ? '#ea580c' : '#2563eb',
          border: `1px solid ${isOverdue ? '#fed7aa' : '#bfdbfe'}`,
          fontSize: 12, fontWeight: 600, cursor: 'pointer',
          fontFamily: 'Assistant, sans-serif',
        }}>
          <span>📤</span>
          {isOverdue ? 'עדכן — עבר זמן!' : 'עדכן יועצים'}
        </button>
        <button onClick={() => setShowHistory(true)} style={{
          padding: '7px 10px', borderRadius: 7,
          background: 'var(--ybp-row-hover,#f3f4f6)',
          border: '1px solid var(--ybp-border,#e5e7eb)',
          color: 'var(--ybp-ink-faint,#6b7280)',
          fontSize: 12, cursor: 'pointer',
          fontFamily: 'Assistant, sans-serif',
        }}>📋</button>
      </div>

      {showModal && (
        <PlansDistributionModal
          projectId={projectId}
          planName={planName}
          planType={planType}
          onClose={() => setShowModal(false)}
        />
      )}
      {showHistory && (
        <DistributionHistoryPanel
          projectId={projectId}
          onClose={() => setShowHistory(false)}
        />
      )}
    </>
  );
};

// ── PlansDistributionBanner — באנר בתוך plans.jsx ──────────────────────────
const PlansDistributionBanner = ({ projectId }) => {
  const [showModal, setShowModal] = useState(false);
  const [showHistory, setShowHistory] = useState(false);

  const history = getDistHistory(projectId);
  const lastDist = history[0];
  const daysSince = lastDist
    ? Math.floor((Date.now() - new Date(lastDist.sentAt).getTime()) / 86400000)
    : null;
  const isOverdue = daysSince === null || daysSince >= 7;

  return (
    <>
      <div style={{
        margin: '0 0 12px',
        padding: '12px 16px',
        borderRadius: 10,
        background: isOverdue ? '#fff7ed' : '#f0fdf4',
        border: `1px solid ${isOverdue ? '#fed7aa' : '#bbf7d0'}`,
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        gap: 10,
      }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13, fontWeight: 700, color: isOverdue ? '#ea580c' : '#16a34a' }}>
            {isOverdue ? '⚠️ לא הופצו תוכניות לאחרונה' : `✅ הופץ לפני ${daysSince} ימים`}
          </div>
          <div style={{ fontSize: 11, color: 'var(--ybp-ink-faint,#6b7280)', marginTop: 2 }}>
            {lastDist
              ? `${lastDist.planName} · ${lastDist.recipients?.length || 0} נמענים · ${lastDist.sentBy}`
              : 'שלח תוכניות מעודכנות לכל היועצים והקבלנים'
            }
          </div>
        </div>
        <div style={{ display: 'flex', gap: 6, flexShrink: 0 }}>
          <button onClick={() => setShowModal(true)} style={{
            padding: '7px 14px', borderRadius: 7,
            background: isOverdue ? '#ea580c' : '#16a34a',
            color: '#fff', border: 'none',
            fontSize: 12, fontWeight: 600, cursor: 'pointer',
            fontFamily: 'Assistant, sans-serif',
          }}>📤 הפץ</button>
          <button onClick={() => setShowHistory(true)} style={{
            padding: '7px 10px', borderRadius: 7,
            background: 'var(--ybp-row-hover,#f3f4f6)',
            border: '1px solid var(--ybp-border,#e5e7eb)',
            color: 'var(--ybp-ink-faint,#6b7280)',
            fontSize: 12, cursor: 'pointer',
          }}>📋</button>
        </div>
      </div>

      {showModal && (
        <PlansDistributionModal
          projectId={projectId}
          planName="כל התוכניות"
          planType="consultants"
          onClose={() => setShowModal(false)}
        />
      )}
      {showHistory && (
        <DistributionHistoryPanel
          projectId={projectId}
          onClose={() => setShowHistory(false)}
        />
      )}
    </>
  );
};

Object.assign(window, {
  PlansDistributionModal,
  DistributionHistoryPanel,
  DistributeButton,
  PlansDistributionBanner,
});
})();
