/**
 * Protocols Module — פרוטוקולים
 * ProtocolsScreen: Timeline + כרטיסיות מתקפלות + טופס + AI מהקלטה
 * SyncStore key: ybp_sync_store → protocols[]
 */
(function () {

// ── 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' },
};

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

// ── ProtocolTypeBadge ────────────────────────────────────────────────────────
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>
  );
};

// ── AI Summary Generator ──────────────────────────────────────────────────────
const generateAISummary = async (title, participants, type) => {
  if (!window.claude) return null;
  try {
    const prompt = `אתה עוזר לניהול פרויקטי בנייה. צור סיכום פרוטוקול קצר בעברית לפגישה הבאה:
נושא: ${title}
סוג: ${PROTOCOL_TYPES[type]?.label || type}
משתתפים: ${participants}

צור סיכום מקצועי ב-3-4 נקודות בולטות בפורמט:
• [נקודה 1]
• [נקודה 2]
• [נקודה 3]
• החלטות: [החלטה עיקרית]`;

    const text = await window.claude.complete(prompt);
    return text;
  } catch (e) {
    console.warn('AI summary failed:', e);
    return null;
  }
};

// ── Error Boundary לתפיסת crashes ב-ProtocolForm ─────────────────────────────
class ProtocolFormErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null, errorInfo: null };
  }
  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }
  componentDidCatch(error, errorInfo) {
    console.error('[ProtocolForm] crash caught:', error, errorInfo);
    this.setState({ errorInfo });
  }
  render() {
    if (this.state.hasError) {
      return (
        <div style={{ padding: 24, fontFamily: 'Assistant, sans-serif', direction: 'rtl', background: '#fef2f2', minHeight: '100vh' }}>
          <h2 style={{ color: '#991b1b', marginTop: 0 }}>⚠️ שגיאה ב-ProtocolForm</h2>
          <pre style={{ background: '#fff', padding: 14, borderRadius: 8, fontSize: 12, overflow: 'auto', whiteSpace: 'pre-wrap', color: '#7f1d1d' }}>
            {String(this.state.error?.message || this.state.error)}
            {'\n\nStack:\n'}
            {this.state.error?.stack || '(no stack)'}
            {'\n\nComponent stack:\n'}
            {this.state.errorInfo?.componentStack || '(no component stack)'}
          </pre>
          <button onClick={this.props.onCancel} style={{ marginTop: 12, padding: '10px 20px', borderRadius: 7, border: 'none', background: '#1a2c4a', color: '#fff', cursor: 'pointer', fontFamily: 'inherit' }}>
            ← חזרה לרשימה
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}

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

// ── ProtocolForm ──────────────────────────────────────────────────────────────
const ProtocolForm = ({ projectId, initial, fromRecording, onSave, onCancel }) => {
  const { isMobile } = useViewport();
  const today = new Date().toISOString().slice(0,10);
  const [form, setForm] = React.useState({
    title: '',
    projectId: projectId || '',
    type: 'site',
    meetingDate: today,
    participants: '',
    agenda: '',
    summary: '',
    decisions: '',
    nextSteps: '',
    documents: [],
    ...(initial || {}),
    ...(fromRecording ? {
      title: fromRecording.title || '',
      summary: fromRecording.transcript || '',
      meetingDate: fromRecording.date || today,
    } : {}),
  });
  const [errors, setErrors] = React.useState({});
  const [aiLoading, setAiLoading] = React.useState(false);
  const [aiDone, setAiDone] = React.useState(false);

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

  const validate = () => {
    const e = {};
    if (!form.title.trim()) e.title = 'שדה חובה';
    if (!form.projectId) e.projectId = 'יש לבחור פרויקט';
    if (!form.meetingDate) e.meetingDate = 'שדה חובה';
    if (!form.summary.trim()) e.summary = 'יש להזין סיכום';
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const handleAI = async () => {
    if (!form.title) { window.toastError && window.toastError('הזן נושא קודם'); return; }
    setAiLoading(true);
    const result = await generateAISummary(form.title, form.participants, form.type);
    setAiLoading(false);
    if (result) {
      set('summary', result);
      setAiDone(true);
      window.toastSuccess && window.toastSuccess('סיכום AI נוצר');
    } else {
      window.toastError && window.toastError('שגיאה ביצירת סיכום AI');
    }
  };

  const handleSubmit = () => {
    if (!validate()) return;
    onSave({
      ...form,
      id: form.id || genId(),
      createdAt: new Date().toISOString(),
      author: (window.YBP_AUTH?.getSession()?.name) || 'מנהל',
    });
  };

  const projects = (window.YBP_DATA && Array.isArray(window.YBP_DATA.projects)) ? window.YBP_DATA.projects : [];

  return (
    <div style={{ fontFamily: 'Assistant, sans-serif', direction: 'rtl', minHeight: '100vh', background: 'var(--ybp-bg,#f6f7f9)' }}>
      {/* Header */}
      <div style={{
        background: '#1a2c4a', color: '#fff',
        padding: '16px 20px', display: 'flex', alignItems: 'center', gap: 12,
        position: 'sticky', top: 0, zIndex: 50,
      }}>
        <button onClick={onCancel} 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 style={{ flex: 1 }}>
          <h2 style={{ margin: 0, fontSize: 18, fontWeight: 700, color: '#fff' }}>
            {initial ? 'עריכת פרוטוקול' : fromRecording ? 'פרוטוקול מהקלטה' : 'פרוטוקול חדש'}
          </h2>
          {fromRecording && (
            <div style={{ fontSize: 12, color: '#93c5fd', marginTop: 2 }}>🎙 ממולא מהקלטת הפגישה</div>
          )}
        </div>
        <button onClick={handleAI} disabled={aiLoading} style={{
          display: 'flex', alignItems: 'center', gap: 6,
          padding: '8px 14px', borderRadius: 8,
          background: aiDone ? 'rgba(16,185,129,0.2)' : 'rgba(124,58,237,0.25)',
          color: aiDone ? '#6ee7b7' : '#c4b5fd',
          border: `1px solid ${aiDone ? 'rgba(16,185,129,0.3)' : 'rgba(124,58,237,0.3)'}`,
          fontSize: 13, fontWeight: 600, cursor: aiLoading ? 'not-allowed' : 'pointer',
          fontFamily: 'Assistant, sans-serif', opacity: aiLoading ? 0.7 : 1,
        }}>
          {aiLoading ? '⏳' : aiDone ? '✓ AI' : '✨ AI סיכום'}
        </button>
      </div>

      <div style={{ padding: 20, maxWidth: 580, margin: '0 auto', paddingBottom: 40, display: 'flex', flexDirection: 'column', gap: 16 }}>

        <ProtField label="נושא הפגישה" required error={errors.title}>
          <input style={{ ...protInpStyle, borderColor: errors.title ? '#dc2626' : undefined }}
            value={form.title} onChange={e => set('title', e.target.value)}
            placeholder="ישיבת תיאום ספקים — שבוע 12" />
        </ProtField>

        <ProtField label="פרויקט" required error={errors.projectId}>
          <select style={{ ...protInpStyle, borderColor: errors.projectId ? '#dc2626' : undefined }}
            value={form.projectId} onChange={e => set('projectId', e.target.value)}>
            <option value="">בחר פרויקט...</option>
            {(projects || []).filter(p => p && p.id).map(p => <option key={p.id} value={p.id}>{p.name || p.id}</option>)}
          </select>
        </ProtField>

        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 12 }}>
          <ProtField label="סוג פגישה">
            <select style={protInpStyle} value={form.type} onChange={e => set('type', e.target.value)}>
              {Object.entries(PROTOCOL_TYPES).map(([k, v]) => (
                <option key={k} value={k}>{v.icon} {v.label}</option>
              ))}
            </select>
          </ProtField>
          <ProtField label="תאריך פגישה" required error={errors.meetingDate}>
            <input type="date" style={{ ...protInpStyle, direction: 'ltr', textAlign: 'right', borderColor: errors.meetingDate ? '#dc2626' : undefined }}
              value={form.meetingDate} onChange={e => set('meetingDate', e.target.value)} />
          </ProtField>
        </div>

        <ProtField label="משתתפים">
          {typeof window !== 'undefined' && window.ParticipantsPicker
            ? <window.ParticipantsPicker value={form.participants} onChange={v => set('participants', v)} projectId={form.projectId || projectId} />
            : <input style={protInpStyle} value={
                Array.isArray(form.participants)
                  ? form.participants.map(p => p.name).join(', ')
                  : (form.participants || '')
              } onChange={e => set('participants', e.target.value)} placeholder="נתן, יוסי, רוני" />}
        </ProtField>

        <ProtField label="סדר יום">
          <textarea style={{ ...protInpStyle, minHeight: 80, resize: 'vertical' }}
            value={form.agenda || ''} onChange={e => set('agenda', e.target.value)}
            placeholder="• נושא 1&#10;• נושא 2" />
        </ProtField>

        <ProtField label="סיכום הפגישה" required error={errors.summary}>
          <div style={{ position: 'relative' }}>
            <textarea
              style={{ ...protInpStyle, minHeight: 140, resize: 'vertical', borderColor: errors.summary ? '#dc2626' : undefined }}
              value={form.summary} onChange={e => set('summary', e.target.value)}
              placeholder="תוכן הפגישה, נושאים שדנו, נקודות חשובות..." />
            {aiLoading && (
              <div style={{
                position: 'absolute', inset: 0, background: 'rgba(255,255,255,0.8)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                borderRadius: 8, fontSize: 14, color: '#7c3aed', fontWeight: 600,
              }}>
                ✨ מייצר סיכום AI...
              </div>
            )}
          </div>
        </ProtField>

        <ProtField label="החלטות">
          <textarea style={{ ...protInpStyle, minHeight: 80, resize: 'vertical' }}
            value={form.decisions} onChange={e => set('decisions', e.target.value)}
            placeholder="• החלטה 1&#10;• החלטה 2" />
        </ProtField>

        <ProtField label="צעדים הבאים">
          <textarea style={{ ...protInpStyle, minHeight: 80, resize: 'vertical' }}
            value={form.nextSteps} onChange={e => set('nextSteps', e.target.value)}
            placeholder="• [שם] יבצע [משימה] עד [תאריך]" />
        </ProtField>

        {/* Actions */}
        <div style={{ display: 'flex', gap: 10, paddingTop: 8 }}>
          <button onClick={handleSubmit} style={{
            flex: 1, padding: 13, borderRadius: 9,
            background: '#1a2c4a', color: '#fff',
            border: 'none', fontSize: 15, fontWeight: 700, cursor: 'pointer',
            fontFamily: 'Assistant, sans-serif',
          }}>
            {initial ? 'שמור שינויים' : 'שמור פרוטוקול'}
          </button>
          <button onClick={onCancel} style={{
            padding: '13px 20px', borderRadius: 9,
            background: 'var(--ybp-row-hover,#f3f4f6)',
            border: '1px solid var(--ybp-border,#e5e7eb)',
            color: 'var(--ybp-ink,#111827)',
            fontSize: 15, fontWeight: 600, cursor: 'pointer',
            fontFamily: 'Assistant, sans-serif',
          }}>ביטול</button>
        </div>
      </div>
    </div>
  );
};

// ── ProtocolCard (מתקפלת) ─────────────────────────────────────────────────────
const ProtocolCard = ({ protocol, onEdit, onDelete, onViewDetail, defaultOpen }) => {
  const { isMobile } = useViewport();
  const [open, setOpen] = React.useState(defaultOpen || false);
  const [confirmDel, setConfirmDel] = React.useState(false);
  const cfg = PROTOCOL_TYPES[protocol.type] || PROTOCOL_TYPES.office;
  const dateStr = protocol.meetingDate
    ? new Date(protocol.meetingDate).toLocaleDateString('he-IL', { day:'2-digit', month:'2-digit', year:'numeric' })
    : protocol.createdAt
      ? new Date(protocol.createdAt).toLocaleDateString('he-IL', { day:'2-digit', month:'2-digit', year:'numeric' })
      : '—';

  return (
    <div style={{
      background: 'var(--ybp-panel,#fff)',
      border: '1px solid var(--ybp-border,#e5e7eb)',
      borderRadius: 12, overflow: 'hidden',
      marginBottom: 12,
    }}>
      {/* Header — תמיד נראה */}
      <div
        onClick={() => onViewDetail ? onViewDetail(protocol) : setOpen(o => !o)}
        style={{
          padding: '14px 16px', cursor: 'pointer',
          display: 'flex', alignItems: 'flex-start', gap: 12,
          background: open ? 'var(--ybp-row-hover,#f6f7f9)' : 'transparent',
        }}
      >
        {/* Type indicator */}
        <div style={{
          width: 40, height: 40, borderRadius: 10,
          background: cfg.bg, display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontSize: 18, flexShrink: 0,
        }}>{cfg.icon}</div>

        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 8 }}>
            <div style={{ fontWeight: 700, fontSize: 15, color: 'var(--ybp-ink,#111827)', lineHeight: 1.3 }}>
              {protocol.title}
            </div>
            <div style={{ display: 'flex', gap: 6, alignItems: 'center', flexShrink: 0 }}>
              <ProtocolTypeBadge type={protocol.type} />
              <Icon name={open ? 'chevronD' : 'chevronR'} size={16} color="var(--ybp-ink-faint,#9ca3af)" />
            </div>
          </div>
          <div style={{ fontSize: 12, color: 'var(--ybp-ink-faint,#6b7280)', marginTop: 4, display: 'flex', gap: 12, flexWrap: 'wrap' }}>
            <span>📅 {dateStr}</span>
            {protocol.participants && <span>👥 {Array.isArray(protocol.participants) ? protocol.participants.length : (protocol.participants || '').split(',').filter(s => s.trim()).length} משתתפים</span>}
            {protocol.author && <span>✍️ {protocol.author}</span>}
          </div>
        </div>
      </div>

      {/* Body — נפתח */}
      {open && (
        <div style={{ padding: '0 16px 16px', borderTop: '1px solid var(--ybp-border,#e5e7eb)' }}>
          {protocol.participants && (
            <div style={{ marginTop: 12 }}>
              <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--ybp-ink-faint,#6b7280)', letterSpacing: 0.3, textTransform: 'uppercase', marginBottom: 6 }}>משתתפים</div>
              <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                {(Array.isArray(protocol.participants)
                  ? protocol.participants.map(p => p.name || p)
                  : (protocol.participants || '').split(',').map(s => s.trim()).filter(Boolean)
                ).map((name, i) => (
                  <span key={i} style={{
                    padding: '3px 10px', borderRadius: 99, fontSize: 12,
                    background: 'var(--ybp-row-hover,#f3f4f6)', color: 'var(--ybp-ink-soft,#374151)',
                  }}>{name}</span>
                ))}
              </div>
            </div>
          )}

          {protocol.summary && (
            <div style={{ marginTop: 14 }}>
              <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--ybp-ink-faint,#6b7280)', letterSpacing: 0.3, textTransform: 'uppercase', marginBottom: 6 }}>סיכום</div>
              <p style={{ margin: 0, fontSize: 14, color: 'var(--ybp-ink,#111827)', lineHeight: 1.7, whiteSpace: 'pre-wrap' }}>{protocol.summary}</p>
            </div>
          )}

          {protocol.decisions && (
            <div style={{ marginTop: 14 }}>
              <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--ybp-ink-faint,#6b7280)', letterSpacing: 0.3, textTransform: 'uppercase', marginBottom: 6 }}>החלטות</div>
              <p style={{ margin: 0, fontSize: 14, color: 'var(--ybp-ink,#111827)', lineHeight: 1.7, whiteSpace: 'pre-wrap' }}>{protocol.decisions}</p>
            </div>
          )}

          {protocol.nextSteps && (
            <div style={{ marginTop: 14 }}>
              <div style={{ fontSize: 11, fontWeight: 700, color: '#ea580c', letterSpacing: 0.3, textTransform: 'uppercase', marginBottom: 6 }}>צעדים הבאים ⚡</div>
              <p style={{ margin: 0, fontSize: 14, color: 'var(--ybp-ink,#111827)', lineHeight: 1.7, whiteSpace: 'pre-wrap' }}>{protocol.nextSteps}</p>
            </div>
          )}

          {/* Actions */}
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 16 }}>
            {[
              { label: '📤 WA', bg: '#f0fdf4', color: '#16a34a', border: '#bbf7d0', 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');
              }},
              { label: '🖨 הדפס', bg: '#eff6ff', color: '#2563eb', border: '#bfdbfe', onClick: () => window.print() },
              { label: '📄 PDF', bg: '#fffbeb', color: '#92400e', border: '#fde68a', onClick: () => {
                  if (window.YBP_NAV?.openProtocolViewer) window.YBP_NAV.openProtocolViewer(protocol.id);
                  else window.dispatchEvent(new CustomEvent('ybp-nav', { detail: { screen: 'protocolViewer', protocolId: protocol.id } }));
                } },
              { label: 'ערוך', bg: 'var(--ybp-row-hover,#f3f4f6)', color: 'var(--ybp-ink,#111827)', border: 'var(--ybp-border,#e5e7eb)', onClick: () => onEdit(protocol) },
              { label: 'מחק', bg: '#fef2f2', color: '#dc2626', border: '#fecaca', onClick: () => setConfirmDel(true) },
            ].map(btn => (
              <button key={btn.label} onClick={btn.onClick} style={{
                padding: isMobile ? '10px 14px' : '7px 14px',
                minHeight: isMobile ? 44 : 36,
                borderRadius: 8,
                background: btn.bg, color: btn.color, border: `1px solid ${btn.border}`,
                fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'Assistant, sans-serif',
              }}>{btn.label}</button>
            ))}
          </div>
        </div>
      )}

      {confirmDel && (
        <ConfirmDialog isOpen title="מחק פרוטוקול?"
          description="הפעולה אינה הפיכה."
          confirmLabel="מחק" confirmVariant="danger"
          onConfirm={() => { onDelete(protocol.id); setConfirmDel(false); }}
          onCancel={() => setConfirmDel(false)} />
      )}
    </div>
  );
};

// ── ProtocolsScreen (main) ────────────────────────────────────────────────────
const ProtocolsScreen = ({ projectId, onBack, onOpenProtocol, editProtocolId }) => {
  const [protocols, setProtocols] = React.useState(loadProtocols);
  const [view, setView] = React.useState('list'); // list | form
  const [editProtocol, setEditProtocol] = React.useState(null);
  const [fromRecording, setFromRecording] = React.useState(null);
  const [filterType, setFilterType] = React.useState('all');
  const [search, setSearch] = React.useState('');
  const [showFAB, setShowFAB] = React.useState(false);

  // Listen for SyncStore changes
  React.useEffect(() => {
    const unsub = window.SyncStore?.subscribe
      ? window.SyncStore.subscribe(() => setProtocols(loadProtocols()))
      : null;
    return () => unsub && unsub();
  }, []);

  // אם נכנסו עם editProtocolId — לעבור מיד למצב form עריכה
  React.useEffect(() => {
    if (!editProtocolId) return;
    const proto = loadProtocols().find(p => p.id === editProtocolId);
    if (proto) {
      setEditProtocol(proto);
      setView('form');
    }
  }, [editProtocolId]);

  const projectProtocols = projectId
    ? protocols.filter(p => p.projectId === projectId)
    : protocols;

  const filtered = projectProtocols.filter(p => {
    const matchType = filterType === 'all' || p.type === filterType;
    const matchSearch = !search ||
      p.title.includes(search) ||
      (p.summary || '').includes(search) ||
      (p.participants || '').includes(search);
    return matchType && matchSearch;
  });

  // Sort newest first
  const sorted = [...filtered].sort((a, b) =>
    new Date(b.meetingDate || b.createdAt) - new Date(a.meetingDate || a.createdAt)
  );

  const persist = (list) => { setProtocols(list); saveProtocols(list); };

  const handleSave = (form) => {
    if (editProtocol && editProtocol.id) {
      persist(protocols.map(p => p.id === editProtocol.id ? { ...p, ...form } : p));
      window.toastSuccess && window.toastSuccess('פרוטוקול עודכן');
    } else {
      const newP = { ...form, projectId: form.projectId || projectId || '' };
      persist([newP, ...protocols]);
      window.toastSuccess && window.toastSuccess('פרוטוקול נשמר');
    }
    setView('list'); setEditProtocol(null); setFromRecording(null);
  };

  const handleDelete = (id) => {
    persist(protocols.filter(p => p.id !== id));
    window.toastSuccess && window.toastSuccess('פרוטוקול נמחק');
  };

  // ── Hook חייב להיות לפני early return (Rules of Hooks) ───────────────────
  const lastRecording = React.useMemo(() => {
    if (!window.SyncStore) return null;
    const meetings = window.SyncStore.get().meetings || [];
    const recordings = meetings.filter(m => m.transcript);
    return recordings.sort((a,b) => new Date(b.createdAt) - new Date(a.createdAt))[0] || null;
  }, []);

  // ── Form view ──
  if (view === 'form') {
    const onFormCancel = () => { setView('list'); setEditProtocol(null); setFromRecording(null); };
    return (
      <ProtocolFormErrorBoundary onCancel={onFormCancel}>
        <ProtocolForm
          projectId={projectId}
          initial={editProtocol}
          fromRecording={fromRecording}
          onSave={handleSave}
          onCancel={onFormCancel}
        />
      </ProtocolFormErrorBoundary>
    );
  }

  // ── List view ──
  const typeCounts = { all: projectProtocols.length };
  Object.keys(PROTOCOL_TYPES).forEach(k => {
    typeCounts[k] = projectProtocols.filter(p => p.type === k).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)' }}>{projectProtocols.length} פרוטוקולים</div>
          </div>
        </div>
        <button onClick={() => setShowFAB(f => !f)} style={{
          width: 40, height: 40, borderRadius: '50%',
          background: 'rgba(255,255,255,0.15)', color: '#fff',
          border: '1px solid rgba(255,255,255,0.25)', fontSize: 22, cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>+</button>
      </div>

      {/* FAB menu */}
      {showFAB && (
        <div style={{
          position: 'fixed', top: 95, left: 20, zIndex: 1000,
          background: 'var(--ybp-panel,#fff)', borderRadius: 12,
          boxShadow: '0 8px 24px rgba(0,0,0,0.15)',
          border: '1px solid var(--ybp-border,#e5e7eb)',
          padding: 8, minWidth: 200,
        }}>
          <button onClick={() => { setShowFAB(false); setEditProtocol(null); setFromRecording(null); setView('form'); }}
            style={{
              width: '100%', padding: '10px 14px', borderRadius: 8, background: 'none',
              border: 'none', textAlign: 'right', cursor: 'pointer', fontSize: 14,
              color: 'var(--ybp-ink,#111827)', fontFamily: 'Assistant, sans-serif',
              display: 'flex', alignItems: 'center', gap: 10,
            }}>
            <span style={{ fontSize: 18 }}>📝</span> פרוטוקול ידני
          </button>
          <button onClick={() => {
            setShowFAB(false);
            if (lastRecording) {
              setFromRecording(lastRecording);
              setView('form');
              window.toastInfo && window.toastInfo('ממלא מהקלטה אחרונה...');
            } else {
              window.toastError && window.toastError('אין הקלטות שמורות — הקלט פגישה קודם');
            }
          }}
            style={{
              width: '100%', padding: '10px 14px', borderRadius: 8, background: 'none',
              border: 'none', textAlign: 'right', cursor: 'pointer', fontSize: 14,
              color: lastRecording ? 'var(--ybp-ink,#111827)' : 'var(--ybp-ink-faint,#9ca3af)',
              fontFamily: 'Assistant, sans-serif',
              display: 'flex', alignItems: 'center', gap: 10,
            }}>
            <span style={{ fontSize: 18 }}>🎙</span>
            מהקלטת פגישה
            {!lastRecording && <span style={{ fontSize: 11, marginRight: 'auto', color: '#9ca3af' }}>אין הקלטות</span>}
          </button>
          {/* Close on backdrop */}
          <div style={{ position: 'fixed', inset: 0, zIndex: -1 }} onClick={() => setShowFAB(false)} />
        </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>

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

      {/* Timeline */}
      <div style={{ padding: '16px 16px 80px' }}>
        {sorted.length === 0 ? (
          <EmptyState
            icon="calendar"
            title={search || filterType !== 'all' ? 'לא נמצאו פרוטוקולים' : 'אין פרוטוקולים עדיין'}
            description={search || filterType !== 'all' ? 'נסה לנקות פילטרים' : 'תעד את הפגישות הראשונות שלך'}
            primaryAction={
              search || filterType !== 'all'
                ? { label: 'נקה פילטרים', onClick: () => { setSearch(''); setFilterType('all'); } }
                : { label: '+ פרוטוקול חדש', onClick: () => setView('form') }
            }
          />
        ) : (
          <div style={{ position: 'relative' }}>
            {/* Timeline line */}
            <div style={{
              position: 'absolute', right: 32, top: 0, bottom: 0,
              width: 2, background: 'var(--ybp-border,#e5e7eb)', zIndex: 0,
            }} />
            {sorted.map((p, i) => (
              <div key={p.id} style={{ position: 'relative', paddingRight: 64, zIndex: 1 }}>
                {/* Timeline dot */}
                <div style={{
                  position: 'absolute', right: 24, top: 26,
                  width: 16, height: 16, borderRadius: '50%',
                  background: PROTOCOL_TYPES[p.type]?.color || '#6b7280',
                  border: '3px solid var(--ybp-bg,#f6f7f9)',
                  zIndex: 2,
                }} />
                <ProtocolCard
                  protocol={p}
                  onEdit={(prot) => { setEditProtocol(prot); setView('form'); }}
                  onDelete={handleDelete}
                  onViewDetail={onOpenProtocol ? (prot) => onOpenProtocol(prot.id) : undefined}
                  defaultOpen={!onOpenProtocol && i === 0}
                />
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
};

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