// ProtocolViewer — תצוגת PDF + נייר מכתבים YBPROJECTS + Print
(function () {
  const { useState, useEffect, useMemo } = React;

  const PROTOCOL_TYPES = {
    zoom:    { label: 'ZOOM',    icon: '💻' },
    site:    { label: 'שטח',    icon: '🏗' },
    phone:   { label: 'טלפון',  icon: '📞' },
    whatsapp:{ label: 'וואטסאפ', icon: '💬' },
    office:  { label: 'משרד',   icon: '🏢' },
  };

  const fmtDateHe = (d) => {
    if (!d) return '';
    const dt = typeof d === 'string' ? new Date(d) : d;
    return dt.toLocaleDateString('he-IL', { day: '2-digit', month: '2-digit', year: 'numeric' });
  };

  const Section = ({ title, children }) => (
    <div style={{ marginBottom: 18 }}>
      <h3 style={{ margin: '0 0 6px', fontSize: 14, color: '#374151', fontWeight: 700, borderBottom: '1.5px solid #e5e7eb', paddingBottom: 4 }}>{title}</h3>
      <div style={{ fontSize: 13, color: '#1f2937', lineHeight: 1.7, whiteSpace: 'pre-wrap' }}>{children}</div>
    </div>
  );

  const ProtocolViewer = ({ protocolId, onBack }) => {
    const [protocol, setProtocol] = useState(null);

    useEffect(() => {
      const protocols = window.SyncStore?.getProtocols?.() || [];
      const p = protocols.find(x => x.id === protocolId);
      setProtocol(p || null);
    }, [protocolId]);

    const project = useMemo(() => {
      if (!protocol) return null;
      const allProjects = window.SyncStore?.get?.()?.projects || window.YBP_DATA?.projects || [];
      return allProjects.find(p => p.id === protocol.projectId) || null;
    }, [protocol]);

    const cfg = protocol ? PROTOCOL_TYPES[protocol.type] || PROTOCOL_TYPES.office : null;
    const dateStr = protocol ? fmtDateHe(protocol.meetingDate || protocol.createdAt) : '';

    const handlePrint = () => window.print();

    if (!protocol) {
      return (
        <div style={{ padding: 40, textAlign: 'center', fontFamily: 'Assistant, sans-serif', direction: 'rtl' }}>
          טוען פרוטוקול...
        </div>
      );
    }

    return (
      <div style={{ fontFamily: 'Assistant, sans-serif', direction: 'rtl', minHeight: '100vh', background: '#f6f7f9' }}>
        {/* Action bar — לא ב-print */}
        <div className="ybp-no-print" style={{ background: '#1a2c4a', color: '#fff', padding: '12px 20px', display: 'flex', alignItems: 'center', gap: 10, position: 'sticky', top: 0, zIndex: 50 }}>
          <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: '6px 12px', borderRadius: 6, fontFamily: 'inherit', fontSize: 13 }}>
            ← חזרה
          </button>
          <div style={{ flex: 1, fontSize: 14, fontWeight: 600 }}>תצוגת פרוטוקול</div>
          <button onClick={() => window.YBP_NAV?.editProtocol?.(protocolId)} style={{ padding: '8px 14px', borderRadius: 7, border: '1px solid rgba(255,255,255,0.25)', background: 'transparent', color: '#e5e7eb', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13, fontWeight: 600 }}>
            ✏️ ערוך
          </button>
          <button onClick={handlePrint} style={{ padding: '8px 14px', borderRadius: 7, border: 'none', background: '#b5a882', color: '#1a2c4a', cursor: 'pointer', fontFamily: 'inherit', fontSize: 13, fontWeight: 700 }}>
            🖨 הדפס / PDF
          </button>
        </div>

        {/* Letterhead */}
        <div id="ybp-protocol-print" style={{ maxWidth: 800, margin: '20px auto', background: '#fff', minHeight: '29.7cm', position: 'relative', boxShadow: '0 4px 20px rgba(0,0,0,0.08)' }}>
          {/* Watermark */}
          <div style={{ position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%,-50%) rotate(-30deg)', fontFamily: 'Georgia, serif', fontSize: 180, color: 'rgba(26,44,74,0.04)', pointerEvents: 'none', userSelect: 'none', zIndex: 0 }}>
            YBP
          </div>

          {/* Header */}
          <div style={{ background: '#ebebeb', padding: '14px 30px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', position: 'relative', zIndex: 1 }}>
            <div style={{ fontSize: 22, fontWeight: 800, color: '#1a2c4a' }}>YBPROJECTS</div>
            <div style={{ fontSize: 11, color: '#6b7280' }}>ניהול פרויקטים בבנייה</div>
          </div>
          <div style={{ height: 3, background: '#b5a882' }} />
          <div style={{ height: 2.5, background: '#1a2c4a' }} />

          {/* Body */}
          <div style={{ padding: '30px 40px', position: 'relative', zIndex: 1, paddingBottom: 80 }}>
            <h1 style={{ margin: '0 0 6px', fontSize: 22, color: '#1a2c4a' }}>סיכום פגישה — {protocol.title}</h1>
            <div style={{ fontSize: 12, color: '#6b7280', marginBottom: 20 }}>
              {project?.name} · {dateStr} · {cfg?.icon} {cfg?.label}
            </div>

            <Section title="משתתפים">
              {Array.isArray(protocol.participants)
                ? protocol.participants.map(p => p.name).join(', ')
                : (protocol.participants || '—')}
            </Section>

            {protocol.agenda    && <Section title="סדר יום">{protocol.agenda}</Section>}
            {protocol.summary   && <Section title="סיכום">{protocol.summary}</Section>}
            {protocol.decisions && <Section title="החלטות">{protocol.decisions}</Section>}
            {protocol.nextSteps && <Section title="צעדים הבאים">{protocol.nextSteps}</Section>}

            <div style={{ marginTop: 40, fontSize: 11, color: '#9ca3af', textAlign: 'left' }}>
              נכתב ע"י: {protocol.author || 'מנהל'} · נוצר: {fmtDateHe(protocol.createdAt)}
            </div>
          </div>

          {/* Footer */}
          <div style={{ background: '#c8bfa8', padding: '12px 30px', display: 'flex', justifyContent: 'space-between', fontSize: 11, color: '#1a2c4a', position: 'absolute', bottom: 0, left: 0, right: 0 }}>
            <span>YBPROJECTS · ניהול פרויקטים בבנייה</span>
            <span>yuval@ybprojects.com</span>
          </div>
        </div>

        {/* Print stylesheet */}
        <style>{`
          @media print {
            html, body { background: #fff !important; margin: 0 !important; padding: 0 !important; }
            body * { -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; color-adjust: exact !important; }
            .ybp-no-print { display: none !important; }
            #ybp-protocol-print {
              box-shadow: none !important;
              margin: 0 !important;
              max-width: 100% !important;
              min-height: auto !important;
            }
            @page { size: A4; margin: 1.2cm; }
          }
        `}</style>
      </div>
    );
  };

  window.ProtocolViewer = ProtocolViewer;
})();
