/**
 * Protocol Detail — פרטי פרוטוקול
 * ProtocolDetailPage: מסך מלא לצפייה ועריכת פרוטוקול
 * ParticipantsPicker: בחירת משתתפים מ-CRM + הוספה ידנית
 * SendProtocolModal: שליחה במייל + עדכון סטטוס
 */
(function () {
const { useState, useEffect, useRef, useCallback, useMemo } = React;

// ── Constants ──────────────────────────────────────────────────────────────────
const PROTOCOL_TYPES = {
  zoom:     { label: 'ZOOM',     icon: '💻', color: '#2563eb', bg: '#eff6ff' },
  site:     { label: 'שטח',     icon: '🏗',  color: '#ea580c', bg: '#fff7ed' },
  phone:    { label: 'טלפון',   icon: '📞', color: '#16a34a', bg: '#f0fdf4' },
  whatsapp: { label: 'וואטסאפ', icon: '💬', color: '#16a34a', bg: '#f0fdf4' },
  office:   { label: 'משרד',    icon: '🏢', color: '#7c3aed', bg: '#f5f3ff' },
};

const STATUS_CFG = {
  draft:       { label: 'טיוטה',   color: '#92400e', bg: '#fffbeb', border: '#fde68a' },
  distributed: { label: 'הופץ',   color: '#166534', bg: '#f0fdf4', border: '#bbf7d0' },
  signed:      { label: 'נחתם',   color: '#1e40af', bg: '#eff6ff', border: '#bfdbfe' },
};

// ── Helpers ────────────────────────────────────────────────────────────────────
function parseParticipants(val) {
  if (!val) return [];
  if (Array.isArray(val)) return val;
  return val.split(',')
    .map(s => s.trim())
    .filter(Boolean)
    .map((s, i) => ({ id: 'p_legacy_' + i, name: s, source: 'manual' }));
}

function formatDate(iso) {
  if (!iso) return '—';
  try {
    return new Date(iso).toLocaleDateString('he-IL', { day: '2-digit', month: '2-digit', year: 'numeric' });
  } catch { return iso; }
}

function formatDuration(sec) {
  if (!sec) return null;
  const m = Math.floor(sec / 60);
  const s = sec % 60;
  return `${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`;
}

function getProtocol(id) {
  if (!window.SyncStore?.getProtocols) return null;
  return window.SyncStore.getProtocols().find(p => p.id === id) || null;
}

// ── Shared UI ──────────────────────────────────────────────────────────────────
const SectionLabel = ({ children }) => (
  <div style={{
    fontSize: 11, fontWeight: 700, color: 'var(--ybp-ink-faint,#6b7280)',
    letterSpacing: 0.5, textTransform: 'uppercase', marginBottom: 8,
  }}>{children}</div>
);

const ProtocolTypeBadge = ({ type }) => {
  const cfg = PROTOCOL_TYPES[type] || PROTOCOL_TYPES.office;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      padding: '3px 10px', borderRadius: 99, fontSize: 12, fontWeight: 600,
      background: cfg.bg, color: cfg.color,
    }}>
      {cfg.icon} {cfg.label}
    </span>
  );
};

// ── ParticipantsPicker ─────────────────────────────────────────────────────────
const ParticipantsPicker = ({ value, onChange, projectId }) => {
  const { isMobile } = useViewport();
  const [open, setOpen] = useState(false);
  const [search, setSearch] = useState('');
  const [showManual, setShowManual] = useState(false);
  const [manual, setManual] = useState({ name: '', role: '', email: '', phone: '' });
  const popRef = useRef(null);

  const selected = useMemo(() => parseParticipants(value), [value]);

  // Load candidates from CRM
  const candidates = useMemo(() => {
    const customers = window.SyncStore?.getCustomers?.() || [];
    const vendors   = window.SyncStore?.getVendors?.()   || [];
    const all = [
      ...customers.map(c => ({ id: c.id || ('c_' + c.name), name: c.name, role: c.role || 'לקוח',    email: c.email || '', phone: c.phone || '', source: 'crm' })),
      ...vendors.map(v =>   ({ id: v.id || ('v_' + v.name), name: v.name, role: v.category || 'ספק', email: v.email || '', phone: v.phone || '', source: 'vendor' })),
    ];
    return all.filter(c => c.name);
  }, [open]);

  const filtered = candidates.filter(c =>
    !search || c.name.includes(search) || (c.role || '').includes(search)
  );

  const isSelected = (id) => selected.some(p => p.id === id);

  const toggle = (candidate) => {
    const next = isSelected(candidate.id)
      ? selected.filter(p => p.id !== candidate.id)
      : [...selected, candidate];
    onChange(next);
  };

  const addManual = () => {
    if (!manual.name.trim()) return;
    const newP = { id: 'p_' + Date.now().toString(36), name: manual.name.trim(), role: manual.role.trim(), email: manual.email.trim(), phone: manual.phone.trim(), source: 'manual' };
    onChange([...selected, newP]);
    setManual({ name: '', role: '', email: '', phone: '' });
    setShowManual(false);
  };

  const removeParticipant = (id) => onChange(selected.filter(p => p.id !== id));

  // Close on outside click (desktop)
  useEffect(() => {
    if (!open || isMobile) return;
    const handler = (e) => { if (popRef.current && !popRef.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, [open, isMobile]);

  const inpSt = {
    width: '100%', padding: '9px 11px', borderRadius: 7,
    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',
  };

  const pickerContent = (
    <div style={{ display: 'flex', flexDirection: 'column', height: isMobile ? '70vh' : 380 }}>
      {/* Search */}
      <div style={{ padding: '12px 14px 8px', borderBottom: '1px solid var(--ybp-border,#e5e7eb)' }}>
        <input
          autoFocus
          value={search}
          onChange={e => setSearch(e.target.value)}
          placeholder="חיפוש לפי שם או תפקיד..."
          style={inpSt}
        />
      </div>

      {/* List */}
      <div style={{ flex: 1, overflowY: 'auto', padding: '8px 0' }}>
        {filtered.length === 0 && !showManual && (
          <div style={{ padding: '20px 16px', textAlign: 'center', color: 'var(--ybp-ink-faint,#9ca3af)', fontSize: 13 }}>
            לא נמצאו אנשי קשר
          </div>
        )}
        {filtered.map(c => (
          <div
            key={c.id}
            onClick={() => toggle(c)}
            style={{
              display: 'flex', alignItems: 'center', gap: 10,
              padding: '10px 14px', cursor: 'pointer',
              background: isSelected(c.id) ? 'var(--ybp-row-hover,#f0f4f8)' : 'transparent',
            }}
          >
            <div style={{
              width: 20, height: 20, borderRadius: 4, flexShrink: 0,
              border: `2px solid ${isSelected(c.id) ? '#1a2c4a' : 'var(--ybp-border,#e5e7eb)'}`,
              background: isSelected(c.id) ? '#1a2c4a' : 'transparent',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              {isSelected(c.id) && <span style={{ color: '#fff', fontSize: 11, lineHeight: 1 }}>✓</span>}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ybp-ink,#111827)' }}>{c.name}</div>
              {c.role && <div style={{ fontSize: 12, color: 'var(--ybp-ink-faint,#6b7280)' }}>{c.role}</div>}
            </div>
            <div style={{ fontSize: 11, color: 'var(--ybp-ink-faint,#9ca3af)', flexShrink: 0 }}>
              {c.source === 'crm' ? '👤' : '🔧'}
            </div>
          </div>
        ))}
      </div>

      {/* Manual add */}
      <div style={{ borderTop: '1px solid var(--ybp-border,#e5e7eb)', padding: 12 }}>
        {!showManual ? (
          <button onClick={() => setShowManual(true)} style={{
            width: '100%', padding: '9px', borderRadius: 7,
            border: '1.5px dashed var(--ybp-border,#e5e7eb)', background: 'transparent',
            color: 'var(--ybp-ink-soft,#374151)', fontSize: 13, cursor: 'pointer',
            fontFamily: 'Assistant, sans-serif',
          }}>+ הוסף ידנית</button>
        ) : (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            <input style={{ ...inpSt, fontSize: 13, padding: '7px 10px' }} placeholder="שם *" value={manual.name} onChange={e => setManual(m => ({...m, name: e.target.value}))} />
            <input style={{ ...inpSt, fontSize: 13, padding: '7px 10px' }} placeholder="תפקיד" value={manual.role} onChange={e => setManual(m => ({...m, role: e.target.value}))} />
            <input style={{ ...inpSt, fontSize: 13, padding: '7px 10px', direction:'ltr' }} placeholder="מייל" value={manual.email} onChange={e => setManual(m => ({...m, email: e.target.value}))} />
            <input style={{ ...inpSt, fontSize: 13, padding: '7px 10px', direction:'ltr' }} placeholder="טלפון" value={manual.phone} onChange={e => setManual(m => ({...m, phone: e.target.value}))} />
            <div style={{ display: 'flex', gap: 6 }}>
              <button onClick={addManual} disabled={!manual.name.trim()} style={{
                flex: 1, padding: '8px', borderRadius: 7, border: 'none',
                background: manual.name.trim() ? '#1a2c4a' : '#e5e7eb',
                color: manual.name.trim() ? '#fff' : '#9ca3af',
                fontSize: 13, fontWeight: 700, cursor: manual.name.trim() ? 'pointer' : 'not-allowed',
                fontFamily: 'Assistant, sans-serif',
              }}>הוסף</button>
              <button onClick={() => setShowManual(false)} style={{
                padding: '8px 12px', borderRadius: 7, border: '1px solid var(--ybp-border,#e5e7eb)',
                background: 'transparent', color: 'var(--ybp-ink-soft,#374151)',
                fontSize: 13, cursor: 'pointer', fontFamily: 'Assistant, sans-serif',
              }}>ביטול</button>
            </div>
          </div>
        )}
      </div>

      {/* Done button (mobile) */}
      {isMobile && (
        <div style={{ padding: '0 12px 12px' }}>
          <button onClick={() => setOpen(false)} style={{
            width: '100%', padding: 12, borderRadius: 9, border: 'none',
            background: '#1a2c4a', color: '#fff', fontSize: 15, fontWeight: 700,
            cursor: 'pointer', fontFamily: 'Assistant, sans-serif',
          }}>סיום ({selected.length})</button>
        </div>
      )}
    </div>
  );

  return (
    <div style={{ position: 'relative' }}>
      {/* Selected chips */}
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: selected.length ? 8 : 0 }}>
        {selected.map(p => (
          <span key={p.id} style={{
            display: 'inline-flex', alignItems: 'center', gap: 5,
            padding: '4px 10px', borderRadius: 99, fontSize: 12, fontWeight: 600,
            background: 'var(--ybp-row-hover,#f0f4f8)', color: 'var(--ybp-ink,#111827)',
            border: '1px solid var(--ybp-border,#e5e7eb)',
          }}>
            {p.name}
            <span onClick={() => removeParticipant(p.id)} style={{ cursor: 'pointer', color: '#9ca3af', fontWeight: 400, fontSize: 13, lineHeight: 1 }}>×</span>
          </span>
        ))}
      </div>

      {/* Trigger */}
      <button
        onClick={() => setOpen(o => !o)}
        style={{
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '9px 12px', borderRadius: 8,
          border: '1.5px solid var(--ybp-border,#e5e7eb)',
          background: 'var(--ybp-input-bg,#fff)', color: 'var(--ybp-ink-soft,#374151)',
          fontSize: 14, cursor: 'pointer', fontFamily: 'Assistant, sans-serif',
          minHeight: 44,
        }}
      >
        <span>👥</span>
        <span>{selected.length > 0 ? `${selected.length} משתתפים נבחרו` : 'בחר משתתפים...'}</span>
      </button>

      {/* Mobile: bottom-sheet */}
      {open && isMobile && (
        <div style={{ position: 'fixed', inset: 0, zIndex: 9000 }}>
          <div onClick={() => setOpen(false)} style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.4)' }} />
          <div style={{
            position: 'absolute', bottom: 0, left: 0, right: 0,
            background: 'var(--ybp-panel,#fff)', borderRadius: '16px 16px 0 0',
            maxHeight: '85vh', display: 'flex', flexDirection: 'column',
            fontFamily: 'Assistant, sans-serif', direction: 'rtl',
          }}>
            <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--ybp-border,#e5e7eb)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <span style={{ fontSize: 16, fontWeight: 700, color: 'var(--ybp-ink,#111827)' }}>בחר משתתפים</span>
              <button onClick={() => setOpen(false)} style={{ background: 'none', border: 'none', fontSize: 20, cursor: 'pointer', color: 'var(--ybp-ink-faint,#9ca3af)' }}>×</button>
            </div>
            {pickerContent}
          </div>
        </div>
      )}

      {/* Desktop: popover */}
      {open && !isMobile && (
        <div ref={popRef} style={{
          position: 'absolute', top: '100%', right: 0, zIndex: 500, marginTop: 4,
          width: 340, background: 'var(--ybp-panel,#fff)',
          border: '1px solid var(--ybp-border,#e5e7eb)', borderRadius: 12,
          boxShadow: '0 8px 24px rgba(0,0,0,0.12)',
          fontFamily: 'Assistant, sans-serif', direction: 'rtl',
          overflow: 'hidden',
        }}>
          {pickerContent}
        </div>
      )}
    </div>
  );
};

// ── SendProtocolModal ──────────────────────────────────────────────────────────
const SendProtocolModal = ({ protocol, onClose }) => {
  const { isMobile } = useViewport();
  const participants = parseParticipants(protocol.participants);
  const [selectedEmails, setSelectedEmails] = useState(
    participants.filter(p => p.email).map(p => p.email)
  );
  const [extraEmail, setExtraEmail] = useState('');
  const [subject, setSubject] = useState(`סיכום פגישה — ${protocol.title} — ${formatDate(protocol.meetingDate)}`);
  const [message, setMessage] = useState('שלום,\n\nמצורף סיכום הפגישה שהתקיימה.\n\nבברכה');
  const [attachPdf, setAttachPdf] = useState(true);
  const [sent, setSent] = useState(false);

  const toggleEmail = (email) => {
    setSelectedEmails(prev =>
      prev.includes(email) ? prev.filter(e => e !== email) : [...prev, email]
    );
  };

  const allEmails = [
    ...selectedEmails,
    ...(extraEmail.trim() ? [extraEmail.trim()] : []),
  ];

  const handleSend = () => {
    const summaryText = `${protocol.summary || ''}\n\n${protocol.decisions ? 'החלטות:\n' + protocol.decisions : ''}${protocol.nextSteps ? '\n\nצעדים הבאים:\n' + protocol.nextSteps : ''}`.trim();
    const bodyText = `${message}\n\n---\n${summaryText}`;
    const gmailUrl = `https://mail.google.com/mail/?view=cm&fs=1&to=${encodeURIComponent(allEmails.join(','))}&su=${encodeURIComponent(subject)}&body=${encodeURIComponent(bodyText)}`;
    window.open(gmailUrl, '_blank');
    if (window.SyncStore?.updateProtocol) {
      window.SyncStore.updateProtocol(protocol.id, {
        status: 'distributed',
        distributedAt: new Date().toISOString(),
        distributedTo: allEmails,
      });
    }
    setSent(true);
    setTimeout(onClose, 1500);
  };

  const inpSt = {
    width: '100%', padding: '9px 11px', borderRadius: 7,
    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',
  };

  const content = (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 16, padding: 20, overflowY: 'auto', flex: 1 }}>
      {sent ? (
        <div style={{ textAlign: 'center', padding: 40 }}>
          <div style={{ fontSize: 48, marginBottom: 12 }}>✅</div>
          <div style={{ fontSize: 18, fontWeight: 700, color: '#166534' }}>Gmail נפתח!</div>
          <div style={{ fontSize: 13, color: 'var(--ybp-ink-faint,#6b7280)', marginTop: 4 }}>הפרוטוקול סומן כ"הופץ"</div>
        </div>
      ) : (
        <>
          {/* Recipients */}
          {participants.filter(p => p.email).length > 0 && (
            <div>
              <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--ybp-ink-soft,#374151)', marginBottom: 8 }}>נמענים</div>
              {participants.filter(p => p.email).map(p => (
                <div key={p.id} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 0' }}>
                  <input
                    type="checkbox"
                    checked={selectedEmails.includes(p.email)}
                    onChange={() => toggleEmail(p.email)}
                    style={{ width: 16, height: 16, accentColor: '#1a2c4a' }}
                  />
                  <div>
                    <span style={{ fontSize: 14, fontWeight: 600, color: 'var(--ybp-ink,#111827)' }}>{p.name}</span>
                    <span style={{ fontSize: 12, color: 'var(--ybp-ink-faint,#6b7280)', marginRight: 8, direction: 'ltr' }}>{p.email}</span>
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* Extra email */}
          <div>
            <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--ybp-ink-soft,#374151)', marginBottom: 6 }}>הוסף נמען נוסף</div>
            <input style={{ ...inpSt, direction: 'ltr' }} placeholder="email@example.com" value={extraEmail} onChange={e => setExtraEmail(e.target.value)} />
          </div>

          {/* Subject */}
          <div>
            <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--ybp-ink-soft,#374151)', marginBottom: 6 }}>נושא</div>
            <input style={inpSt} value={subject} onChange={e => setSubject(e.target.value)} />
          </div>

          {/* Message */}
          <div>
            <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--ybp-ink-soft,#374151)', marginBottom: 6 }}>הודעה</div>
            <textarea style={{ ...inpSt, minHeight: 90, resize: 'vertical' }} value={message} onChange={e => setMessage(e.target.value)} />
          </div>

          {/* Attach PDF */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 12px', borderRadius: 8, background: 'var(--ybp-row-hover,#f9fafb)', border: '1px solid var(--ybp-border,#e5e7eb)' }}>
            <input type="checkbox" checked={attachPdf} onChange={e => setAttachPdf(e.target.checked)} style={{ width: 16, height: 16, accentColor: '#1a2c4a' }} />
            <span style={{ fontSize: 13, color: 'var(--ybp-ink,#111827)' }}>📎 צרף PDF סיכום</span>
            <span style={{ fontSize: 11, color: 'var(--ybp-ink-faint,#9ca3af)' }}>(יש ל-Export ידנית ול-Attach ב-Gmail)</span>
          </div>

          {/* Send */}
          <button
            onClick={handleSend}
            disabled={allEmails.length === 0}
            style={{
              padding: '13px', borderRadius: 9, border: 'none',
              background: allEmails.length > 0 ? '#1a2c4a' : '#e5e7eb',
              color: allEmails.length > 0 ? '#fff' : '#9ca3af',
              fontSize: 15, fontWeight: 700, cursor: allEmails.length > 0 ? 'pointer' : 'not-allowed',
              fontFamily: 'Assistant, sans-serif',
            }}
          >
            📧 פתח Gmail ושלח ({allEmails.length})
          </button>
        </>
      )}
    </div>
  );

  if (isMobile) {
    return (
      <div style={{ position: 'fixed', inset: 0, zIndex: 9500, background: 'var(--ybp-bg,#f6f7f9)', display: 'flex', flexDirection: 'column', fontFamily: 'Assistant, sans-serif', direction: 'rtl' }}>
        <div style={{ background: '#1a2c4a', color: '#fff', padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12 }}>
          <button onClick={onClose} style={{ background: 'rgba(255,255,255,0.12)', border: 'none', color: '#fff', fontSize: 18, cursor: 'pointer', borderRadius: 6, width: 32, height: 32, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>×</button>
          <h2 style={{ margin: 0, fontSize: 17, fontWeight: 700 }}>שליחת פרוטוקול</h2>
        </div>
        {content}
      </div>
    );
  }

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 9500, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'Assistant, sans-serif', direction: 'rtl' }}>
      <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.4)' }} />
      <div style={{ position: 'relative', background: 'var(--ybp-panel,#fff)', borderRadius: 16, width: 480, maxWidth: '95vw', maxHeight: '90vh', overflow: 'hidden', display: 'flex', flexDirection: 'column', boxShadow: '0 20px 60px rgba(0,0,0,0.25)' }}>
        <div style={{ background: '#1a2c4a', color: '#fff', padding: '16px 20px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <h2 style={{ margin: 0, fontSize: 17, fontWeight: 700 }}>שליחת פרוטוקול</h2>
          <button onClick={onClose} style={{ background: 'rgba(255,255,255,0.12)', border: 'none', color: '#fff', fontSize: 18, cursor: 'pointer', borderRadius: 6, width: 32, height: 32, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>×</button>
        </div>
        {content}
      </div>
    </div>
  );
};

// ── ProtocolDetailPage ─────────────────────────────────────────────────────────
const ProtocolDetailPage = ({ protocolId, onBack, onEdit }) => {
  const { isMobile } = useViewport();
  const [protocol, setProtocol] = useState(() => getProtocol(protocolId));
  const [showTranscript, setShowTranscript] = useState(false);
  const [showMenu, setShowMenu] = useState(false);
  const [showSendModal, setShowSendModal] = useState(false);
  const [tasksAdded, setTasksAdded] = useState(false);
  const [markingDist, setMarkingDist] = useState(false);

  // Subscribe to SyncStore changes
  useEffect(() => {
    const unsub = window.SyncStore?.subscribe
      ? window.SyncStore.subscribe(() => setProtocol(getProtocol(protocolId)))
      : null;
    return () => unsub?.();
  }, [protocolId]);

  if (!protocol) {
    return (
      <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'Assistant, sans-serif', direction: 'rtl' }}>
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontSize: 40, marginBottom: 12 }}>📭</div>
          <div style={{ fontSize: 16, color: 'var(--ybp-ink-faint,#6b7280)' }}>הפרוטוקול לא נמצא</div>
          <button onClick={onBack} style={{ marginTop: 16, padding: '10px 20px', borderRadius: 8, border: 'none', background: '#1a2c4a', color: '#fff', fontSize: 14, cursor: 'pointer', fontFamily: 'inherit' }}>חזרה</button>
        </div>
      </div>
    );
  }

  const cfg = PROTOCOL_TYPES[protocol.type] || PROTOCOL_TYPES.office;
  const statusCfg = STATUS_CFG[protocol.status] || STATUS_CFG.draft;
  const participants = parseParticipants(protocol.participants);
  const dateStr = formatDate(protocol.meetingDate || protocol.createdAt);
  const duration = formatDuration(protocol.audioDuration);

  const updateProtocol = useCallback((updates) => {
    if (window.SyncStore?.updateProtocol) {
      window.SyncStore.updateProtocol(protocol.id, updates);
    }
  }, [protocol.id]);

  const addAllTasks = () => {
    const tasks = protocol.extractedTasks || [];
    if (!tasks.length) return;
    tasks.forEach(t => {
      window.SyncStore?.addTask?.({
        id: 'task_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 5),
        projectId: protocol.projectId,
        title: t.title,
        assignee: t.assignee || '',
        due: t.due || '',
        status: 'open',
        source: 'protocol',
        protocolId: protocol.id,
      });
    });
    setTasksAdded(true);
    window.toastSuccess?.('משימות נוספו לפרויקט ✓');
  };

  const markDistributed = () => {
    setMarkingDist(true);
    updateProtocol({ status: 'distributed', distributedAt: new Date().toISOString() });
    window.toastSuccess?.('פרוטוקול סומן כ"הופץ" ✓');
    setTimeout(() => setMarkingDist(false), 2000);
  };

  const handleDelete = () => {
    if (!window.confirm('למחוק פרוטוקול זה?')) return;
    const protocols = window.SyncStore?.getProtocols?.() || [];
    if (window.SyncStore?.saveProtocols) {
      window.SyncStore.saveProtocols(protocols.filter(p => p.id !== protocol.id));
    }
    onBack();
  };

  const cardSt = {
    background: 'var(--ybp-panel,#fff)',
    border: '1px solid var(--ybp-border,#e5e7eb)',
    borderRadius: 12, padding: isMobile ? 14 : 20,
    marginBottom: 12,
  };

  const sectionTitleSt = {
    fontSize: 11, fontWeight: 700, color: 'var(--ybp-ink-faint,#6b7280)',
    letterSpacing: 0.5, textTransform: 'uppercase', marginBottom: 10,
  };

  return (
    <div style={{ minHeight: '100vh', background: 'var(--ybp-bg,#f6f7f9)', fontFamily: 'Assistant, sans-serif', direction: 'rtl', paddingBottom: 80 }}>

      {/* ── A: Sticky header ─────────────────────────────────────────────── */}
      <div style={{
        background: '#1a2c4a', color: '#fff',
        padding: isMobile ? '12px 14px' : '14px 20px',
        display: 'flex', alignItems: 'center', gap: 10,
        position: 'sticky', top: 0, zIndex: 100,
      }}>
        <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, flexShrink: 0,
        }}>← חזרה</button>

        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: isMobile ? 15 : 17, fontWeight: 700, color: '#fff', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
            {protocol.title}
          </div>
          <div style={{ marginTop: 3 }}>
            <ProtocolTypeBadge type={protocol.type} />
          </div>
        </div>

        {/* ⋯ menu */}
        <div style={{ position: 'relative', flexShrink: 0 }}>
          <button onClick={() => setShowMenu(m => !m)} style={{
            background: 'rgba(255,255,255,0.12)', border: 'none', color: '#fff',
            width: 36, height: 36, borderRadius: 8, cursor: 'pointer', fontSize: 18,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>⋯</button>
          {showMenu && (
            <div style={{
              position: 'absolute', top: '100%', left: 0, marginTop: 4, zIndex: 200,
              background: 'var(--ybp-panel,#fff)', borderRadius: 10,
              boxShadow: '0 8px 24px rgba(0,0,0,0.15)', border: '1px solid var(--ybp-border,#e5e7eb)',
              minWidth: 160, overflow: 'hidden', direction: 'rtl',
            }}>
              {[
                { icon: '✏️', label: 'ערוך', action: () => { setShowMenu(false); onEdit?.(); } },
                { icon: '📤', label: 'שלח במייל', action: () => { setShowMenu(false); setShowSendModal(true); } },
                { icon: '🖨', label: 'הדפס', action: () => { setShowMenu(false); window.print(); } },
                { icon: '🗑', label: 'מחק', action: () => { setShowMenu(false); handleDelete(); }, danger: true },
              ].map(item => (
                <button key={item.label} onClick={item.action} style={{
                  width: '100%', padding: '10px 14px', background: 'none', border: 'none',
                  textAlign: 'right', cursor: 'pointer', fontSize: 14, display: 'flex',
                  alignItems: 'center', gap: 8, color: item.danger ? '#dc2626' : 'var(--ybp-ink,#111827)',
                  fontFamily: 'Assistant, sans-serif',
                }}>
                  <span>{item.icon}</span> {item.label}
                </button>
              ))}
            </div>
          )}
          {showMenu && <div style={{ position: 'fixed', inset: 0, zIndex: 199 }} onClick={() => setShowMenu(false)} />}
        </div>
      </div>

      <div style={{ padding: isMobile ? '12px 12px 0' : '20px 20px 0', maxWidth: 720, margin: '0 auto' }}>

        {/* ── B: Meta bar ────────────────────────────────────────────────── */}
        <div style={{ ...cardSt, display: 'flex', flexWrap: 'wrap', gap: 12, alignItems: 'center' }}>
          <span style={{ fontSize: 14, color: 'var(--ybp-ink-soft,#374151)' }}>📅 {dateStr}</span>
          {duration && <span style={{ fontSize: 14, color: 'var(--ybp-ink-soft,#374151)' }}>⏱ {duration}</span>}
          {protocol.author && <span style={{ fontSize: 14, color: 'var(--ybp-ink-soft,#374151)' }}>✍️ {protocol.author}</span>}
          {protocol.source === 'recording' && (
            <button onClick={() => setShowTranscript(s => !s)} style={{
              padding: '5px 12px', borderRadius: 7, border: '1px solid #bfdbfe',
              background: showTranscript ? '#eff6ff' : 'transparent',
              color: '#2563eb', fontSize: 12, fontWeight: 600, cursor: 'pointer',
              fontFamily: 'inherit',
            }}>
              🎙 {showTranscript ? 'הסתר תמלול' : 'הצג תמלול ואודיו'}
            </button>
          )}
          {/* Status badge */}
          <span style={{
            marginRight: 'auto', padding: '4px 12px', borderRadius: 99, fontSize: 12, fontWeight: 600,
            background: statusCfg.bg, color: statusCfg.color, border: `1px solid ${statusCfg.border}`,
          }}>
            {statusCfg.label}
          </span>
        </div>

        {/* ── C: Agenda ──────────────────────────────────────────────────── */}
        {protocol.agenda?.trim() && (
          <div style={cardSt}>
            <div style={sectionTitleSt}>סדר יום</div>
            <p style={{ margin: 0, fontSize: 14, color: 'var(--ybp-ink,#111827)', lineHeight: 1.7, whiteSpace: 'pre-wrap' }}>{protocol.agenda}</p>
          </div>
        )}

        {/* ── D: Participants ─────────────────────────────────────────────── */}
        <div style={cardSt}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
            <div style={sectionTitleSt}>משתתפים</div>
          </div>
          {participants.length > 0 ? (
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 10 }}>
              {participants.map(p => (
                <span key={p.id} style={{
                  padding: '5px 12px', borderRadius: 99, fontSize: 13, fontWeight: 600,
                  background: 'var(--ybp-row-hover,#f3f4f6)', color: 'var(--ybp-ink-soft,#374151)',
                  border: '1px solid var(--ybp-border,#e5e7eb)',
                }}>
                  {p.name}{p.role ? ` · ${p.role}` : ''}
                </span>
              ))}
            </div>
          ) : (
            <p style={{ margin: '0 0 10px', fontSize: 13, color: 'var(--ybp-ink-faint,#9ca3af)' }}>אין משתתפים מוגדרים</p>
          )}
          <ParticipantsPicker
            value={protocol.participants}
            onChange={val => updateProtocol({ participants: val })}
            projectId={protocol.projectId}
          />
        </div>

        {/* ── E: Summary ─────────────────────────────────────────────────── */}
        {protocol.summary?.trim() && (
          <div style={cardSt}>
            <div style={sectionTitleSt}>סיכום הפגישה</div>
            <p style={{ margin: 0, fontSize: 14, color: 'var(--ybp-ink,#111827)', lineHeight: 1.8, whiteSpace: 'pre-wrap' }}>{protocol.summary}</p>
          </div>
        )}

        {/* ── F: Decisions ───────────────────────────────────────────────── */}
        {protocol.decisions?.trim() && (
          <div style={cardSt}>
            <div style={sectionTitleSt}>החלטות</div>
            <p style={{ margin: 0, fontSize: 14, color: 'var(--ybp-ink,#111827)', lineHeight: 1.8, whiteSpace: 'pre-wrap' }}>{protocol.decisions}</p>
          </div>
        )}

        {/* ── G: Extracted tasks ─────────────────────────────────────────── */}
        {(protocol.extractedTasks || []).length > 0 && (
          <div style={cardSt}>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10, flexWrap: 'wrap', gap: 8 }}>
              <div style={sectionTitleSt}>משימות שחולצו ({protocol.extractedTasks.length})</div>
              <button
                onClick={addAllTasks}
                disabled={tasksAdded}
                style={{
                  padding: '8px 14px', borderRadius: 7, border: 'none',
                  minHeight: 40,
                  background: tasksAdded ? '#f0fdf4' : '#1a2c4a',
                  color: tasksAdded ? '#16a34a' : '#fff',
                  fontSize: 13, fontWeight: 700, cursor: tasksAdded ? 'default' : 'pointer',
                  fontFamily: 'inherit',
                }}
              >
                {tasksAdded ? '✓ נוספו' : '➕ הוסף את כולן'}
              </button>
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {protocol.extractedTasks.map((t, i) => (
                <div key={i} style={{
                  display: 'flex', gap: 10, alignItems: 'flex-start',
                  padding: '10px 12px', borderRadius: 8,
                  background: 'var(--ybp-row-hover,#f9fafb)', border: '1px solid var(--ybp-border,#e5e7eb)',
                }}>
                  <div style={{ width: 8, height: 8, borderRadius: '50%', background: '#3b82f6', flexShrink: 0, marginTop: 5 }} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ybp-ink,#111827)' }}>{t.title}</div>
                    <div style={{ fontSize: 12, color: 'var(--ybp-ink-faint,#6b7280)', marginTop: 3 }}>
                      {t.assignee && <span>👤 {t.assignee}</span>}
                      {t.due && <span style={{ marginRight: 10 }}>📅 {t.due}</span>}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        )}

        {/* ── H: Next steps ──────────────────────────────────────────────── */}
        {protocol.nextSteps?.trim() && (
          <div style={cardSt}>
            <div style={sectionTitleSt}>⚡ צעדים הבאים</div>
            <p style={{ margin: 0, fontSize: 14, color: 'var(--ybp-ink,#111827)', lineHeight: 1.8, whiteSpace: 'pre-wrap' }}>{protocol.nextSteps}</p>
          </div>
        )}

        {/* ── I: Documents ───────────────────────────────────────────────── */}
        {((protocol.documents || []).length > 0 || protocol.driveUrls?.folder) && (
          <div style={cardSt}>
            <div style={sectionTitleSt}>קבצים מצורפים</div>
            {(protocol.documents || []).map((doc, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '8px 0', borderBottom: '1px solid var(--ybp-border,#e5e7eb)' }}>
                <span style={{ fontSize: 18 }}>📄</span>
                <span style={{ flex: 1, fontSize: 14, color: 'var(--ybp-ink,#111827)' }}>{doc.name || doc}</span>
              </div>
            ))}
            {protocol.driveUrls?.folder && (
              <a href={protocol.driveUrls.folder} target="_blank" rel="noreferrer" style={{
                display: 'inline-flex', alignItems: 'center', gap: 6, marginTop: 10,
                padding: '7px 14px', borderRadius: 7, background: '#eff6ff', color: '#2563eb',
                border: '1px solid #bfdbfe', fontSize: 13, fontWeight: 600, textDecoration: 'none',
              }}>☁️ פתח תיקיית Drive</a>
            )}
          </div>
        )}

        {/* ── J: Transcript ──────────────────────────────────────────────── */}
        {protocol.source === 'recording' && showTranscript && protocol.transcript?.trim() && (
          <div style={cardSt}>
            <div style={sectionTitleSt}>🎙 תמלול מלא</div>
            {protocol.driveUrls?.summary && (
              <a href={protocol.driveUrls.summary} target="_blank" rel="noreferrer" style={{
                display: 'inline-flex', alignItems: 'center', gap: 6, marginBottom: 12,
                padding: '6px 12px', borderRadius: 7, background: '#f0fdf4', color: '#16a34a',
                border: '1px solid #bbf7d0', fontSize: 12, fontWeight: 600, textDecoration: 'none',
              }}>📄 פתח תמלול ב-Drive</a>
            )}
            <pre style={{
              margin: 0, fontSize: 13, color: 'var(--ybp-ink-soft,#374151)', lineHeight: 1.7,
              whiteSpace: 'pre-wrap', wordBreak: 'break-word',
              background: 'var(--ybp-bg,#f6f7f9)', padding: 12, borderRadius: 8,
              maxHeight: 300, overflowY: 'auto',
            }}>{protocol.transcript}</pre>
          </div>
        )}

        {/* ── K: Export/Share bar ────────────────────────────────────────── */}
        <div style={{ ...cardSt, display: 'flex', flexDirection: isMobile ? 'column' : 'row', flexWrap: 'wrap', gap: 8 }}>
          {[
            { label: '🖨 PDF', onClick: () => window.print(), border: '#bfdbfe', bg: '#eff6ff', color: '#2563eb' },
            { label: '📧 מייל', onClick: () => setShowSendModal(true), border: 'var(--ybp-border,#e5e7eb)', bg: 'var(--ybp-panel,#fff)', color: 'var(--ybp-ink,#111827)' },
            { label: '📤 WhatsApp', onClick: () => {
              const text = `פרוטוקול: ${protocol.title}\nתאריך: ${dateStr}\n\n${protocol.summary || ''}${protocol.decisions ? '\n\nהחלטות:\n' + protocol.decisions : ''}${protocol.nextSteps ? '\n\nצעדים הבאים:\n' + protocol.nextSteps : ''}`;
              window.open(`https://wa.me/?text=${encodeURIComponent(text)}`, '_blank');
            }, border: '#bbf7d0', bg: '#f0fdf4', color: '#16a34a' },
          ].map(btn => (
            <button key={btn.label} onClick={btn.onClick} style={{
              flex: isMobile ? 'none' : undefined,
              width: isMobile ? '100%' : 'auto',
              padding: isMobile ? '14px' : '9px 14px',
              minHeight: 48,
              borderRadius: 8, border: `1px solid ${btn.border}`,
              background: btn.bg, color: btn.color,
              fontSize: 14, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit',
              display: 'flex', alignItems: 'center', justifyContent: isMobile ? 'center' : 'flex-start', gap: 6,
            }}>{btn.label}</button>
          ))}
        </div>

        {/* ── L: Footer ──────────────────────────────────────────────────── */}
        {protocol.status !== 'distributed' && (
          <div style={{ ...cardSt, display: 'flex', flexDirection: isMobile ? 'column' : 'row', alignItems: isMobile ? 'stretch' : 'center', justifyContent: 'space-between', gap: 12 }}>
            <div>
              <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--ybp-ink,#111827)' }}>סטטוס הפצה</div>
              <div style={{ fontSize: 12, color: 'var(--ybp-ink-faint,#6b7280)' }}>הפרוטוקול עדיין לא הופץ לנמענים</div>
            </div>
            <button
              onClick={markDistributed}
              disabled={markingDist}
              style={{
                padding: isMobile ? '14px' : '10px 18px',
                minHeight: 48,
                borderRadius: 8, border: 'none',
                background: markingDist ? '#f0fdf4' : '#1a2c4a',
                color: markingDist ? '#16a34a' : '#fff',
                fontSize: 14, fontWeight: 700, cursor: markingDist ? 'default' : 'pointer',
                fontFamily: 'inherit', width: isMobile ? '100%' : 'auto',
              }}
            >
              {markingDist ? '✓ הופץ!' : '✓ סמן כהופץ'}
            </button>
          </div>
        )}

      </div>

      {/* Send modal */}
      {showSendModal && <SendProtocolModal protocol={protocol} onClose={() => setShowSendModal(false)} />}
    </div>
  );
};

Object.assign(window, { ProtocolDetailPage, ParticipantsPicker, parseParticipants, SendProtocolModal });
})();
