// ═══════════════════════════════════════════════════════════════
//  Community page — forum + supplier recommendations
//  Features: public + moderators-only channels, multi-image posts,
//  edit-with-history, full comment threads, fullscreen image gallery.
// ═══════════════════════════════════════════════════════════════

const { useState: uSCM, useEffect: uECM, useMemo: uMCM, useRef: uRCM } = React;

// Backward-compat helper: read images from either new `images` array or old `image` single.
window.postImages = function postImages(p) {
  if (Array.isArray(p.images) && p.images.length) return p.images;
  if (p.image) return [p.image];
  return [];
};

// ───────────────────────────────────────────────
//  Image Gallery Modal — fullscreen lightbox with prev/next
// ───────────────────────────────────────────────
window.ImageGalleryModal = function ImageGalleryModal({ images, startIndex = 0, onClose }) {
  const [idx, setIdx] = uSCM(startIndex);
  uECM(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      else if (e.key === 'ArrowLeft') setIdx(i => Math.min(i + 1, images.length - 1));
      else if (e.key === 'ArrowRight') setIdx(i => Math.max(i - 1, 0));
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [images.length, onClose]);
  if (!images?.length) return null;
  return ReactDOM.createPortal(
    <div className="fixed inset-0 z-[200] bg-black/90 flex items-center justify-center animate-fade-in" onClick={onClose} role="dialog" aria-modal="true" aria-label="גלריית תמונות">
      <button
        onClick={onClose}
        aria-label="סגור גלריה"
        className="absolute top-4 left-4 w-11 h-11 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center focus-visible:ring-4 focus-visible:ring-amber-400"
      >
        <window.Icon.X size={24}/>
      </button>
      {images.length > 1 && (
        <>
          <button
            onClick={(e) => { e.stopPropagation(); setIdx(i => Math.max(i - 1, 0)); }}
            disabled={idx === 0}
            aria-label="התמונה הקודמת"
            className="absolute right-4 top-1/2 -translate-y-1/2 w-12 h-12 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center disabled:opacity-30 focus-visible:ring-4 focus-visible:ring-amber-400"
          >
            <window.Icon.ChevronRight size={28}/>
          </button>
          <button
            onClick={(e) => { e.stopPropagation(); setIdx(i => Math.min(i + 1, images.length - 1)); }}
            disabled={idx === images.length - 1}
            aria-label="התמונה הבאה"
            className="absolute left-4 top-1/2 -translate-y-1/2 w-12 h-12 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center disabled:opacity-30 focus-visible:ring-4 focus-visible:ring-amber-400"
          >
            <window.Icon.ChevronLeft size={28}/>
          </button>
        </>
      )}
      <img
        src={images[idx]}
        onClick={e => e.stopPropagation()}
        className="max-w-[92vw] max-h-[88vh] object-contain shadow-2xl rounded-lg"
        alt={`תמונה ${idx + 1} מתוך ${images.length}`}
      />
      {images.length > 1 && (
        <div className="absolute bottom-6 left-1/2 -translate-x-1/2 text-white text-sm font-bold px-4 py-1.5 rounded-full bg-black/60">
          {idx + 1} / {images.length}
        </div>
      )}
    </div>,
    document.body
  );
};

// ───────────────────────────────────────────────
//  Post images block — thumbnails with click-to-gallery
// ───────────────────────────────────────────────
window.PostImages = function PostImages({ images, small = false }) {
  const [galleryIdx, setGalleryIdx] = uSCM(null);
  if (!images?.length) return null;
  const n = images.length;
  const h = small ? 'max-h-52' : 'max-h-80';

  // Single image — large contain (no crop)
  if (n === 1) {
    return (
      <>
        <button
          type="button"
          onClick={e => { e.stopPropagation(); setGalleryIdx(0); }}
          className={`mt-2 block rounded-xl overflow-hidden bg-slate-100 w-full ${h} hover:opacity-90 transition-opacity`}
          aria-label="פתח תמונה במסך מלא"
        >
          <img src={images[0]} alt="" className={`w-full ${h} object-contain`}/>
        </button>
        {galleryIdx != null && <window.ImageGalleryModal images={images} startIndex={galleryIdx} onClose={() => setGalleryIdx(null)}/>}
      </>
    );
  }

  // Multiple — 2-column grid (or 4 for >=4)
  const cols = n === 2 ? 'grid-cols-2' : n === 3 ? 'grid-cols-3' : 'grid-cols-2';
  return (
    <>
      <div className={`mt-2 grid ${cols} gap-1.5`}>
        {images.slice(0, 4).map((src, i) => (
          <button
            key={i}
            type="button"
            onClick={e => { e.stopPropagation(); setGalleryIdx(i); }}
            className="relative rounded-lg overflow-hidden bg-slate-100 aspect-video hover:opacity-90 transition-opacity"
            aria-label={`פתח תמונה ${i + 1}`}
          >
            <img src={src} alt="" className="absolute inset-0 w-full h-full object-cover"/>
            {i === 3 && n > 4 && (
              <div className="absolute inset-0 bg-black/60 flex items-center justify-center text-white font-display font-black text-2xl">
                +{n - 4}
              </div>
            )}
          </button>
        ))}
      </div>
      {galleryIdx != null && <window.ImageGalleryModal images={images} startIndex={galleryIdx} onClose={() => setGalleryIdx(null)}/>}
    </>
  );
};

// ───────────────────────────────────────────────
//  CommunityPage — main forum page
// ───────────────────────────────────────────────
window.CommunityPage = function CommunityPage() {
  const { state, currentUser, likePost, togglePinPost, toggleHidePost, deletePost } = window.useApp();
  const toast = window.useToast();
  const [tab, setTab] = uSCM('posts');
  const [channel, setChannel] = uSCM('public'); // 'public' | 'moderators'
  const [newPostOpen, setNewPostOpen] = uSCM(false);
  const [sortBy, setSortBy] = uSCM('pinned'); // 'pinned' | 'recent' | 'popular'
  const [showHidden, setShowHidden] = uSCM(false);
  const [tagFilter, setTagFilter] = uSCM(null);
  const [openPostId, setOpenPostId] = uSCM(null);

  const isModerator = currentUser.role === 'admin' || currentUser.role === 'national';

  const allPosts = state.communityPosts || [];
  // filter by channel: only moderators see 'moderators' channel
  let posts = allPosts.filter(p => {
    const postChannel = p.channel || 'public';
    if (postChannel === 'moderators') return isModerator;
    return true;
  });
  if (channel === 'moderators') {
    posts = posts.filter(p => (p.channel || 'public') === 'moderators');
  } else {
    posts = posts.filter(p => (p.channel || 'public') === 'public');
  }
  posts = isModerator ? (showHidden ? posts : posts.filter(p => !p.hidden)) : posts.filter(p => !p.hidden);
  if (tagFilter) posts = posts.filter(p => (p.tags || []).includes(tagFilter));
  posts = [...posts].sort((a, b) => {
    if (a.pinned && !b.pinned) return -1;
    if (!a.pinned && b.pinned) return 1;
    if (sortBy === 'popular') return (b.likes || 0) - (a.likes || 0);
    return (b.date || '').localeCompare(a.date || '');
  });

  const allTags = [...new Set(allPosts.flatMap(p => p.tags || []))];
  const recs = state.supplierRecommendations || [];
  const openPost = openPostId ? state.communityPosts.find(p => p.id === openPostId) : null;

  return (
    <div className="animate-fade-in">
      <window.PageHeader
        title="שיתוף קהילה"
        subtitle="פורום רכזים — שיתוף פעילויות, המלצות על ספקים, מדיניות וחדשות"
        actions={
          <window.Button variant="primary" icon={<window.Icon.Plus size={16}/>} onClick={() => setNewPostOpen(true)}>
            פוסט חדש
          </window.Button>
        }
      />

      <div className="surface mb-5 p-2">
        <window.Tabs
          tabs={[
            { value: 'posts', label: 'פורום', count: posts.length },
            { value: 'suppliers', label: 'ספקים מומלצים', count: recs.length }
          ]}
          value={tab} onChange={setTab}
        />
      </div>

      {tab === 'posts' && (
        <>
          {/* Channel switcher (moderators only see the second channel) */}
          {isModerator && (
            <div className="inline-flex rounded-xl bg-white border border-slate-200 p-1 mb-4 shadow-sm">
              <button
                onClick={() => setChannel('public')}
                className={`px-4 py-2 rounded-lg text-sm font-bold transition-colors ${channel === 'public' ? 'bg-brand-600 text-white shadow-sm' : 'text-slate-600 hover:bg-slate-50'}`}
              >
                <window.Icon.FileText size={14} className="inline ml-1.5"/> פורום כללי
              </button>
              <button
                onClick={() => setChannel('moderators')}
                className={`px-4 py-2 rounded-lg text-sm font-bold transition-colors ${channel === 'moderators' ? 'bg-indigo-600 text-white shadow-sm' : 'text-slate-600 hover:bg-slate-50'}`}
              >
                <window.Icon.Shield size={14} className="inline ml-1.5"/> פורום מנהלים
              </button>
            </div>
          )}

          <div className="grid grid-cols-1 lg:grid-cols-4 gap-5">
            {/* SIDEBAR: filters */}
            <aside className="lg:col-span-1 space-y-3">
              <div className="surface p-4">
                <div className="text-xs font-semibold text-slate-500 uppercase tracking-wide mb-2">מיון</div>
                {[{v:'pinned',l:'נעוצים ראשונים'},{v:'recent',l:'החדשים ביותר'},{v:'popular',l:'הפופולריים'}].map(o => (
                  <button key={o.v} onClick={() => setSortBy(o.v)}
                    className={`w-full text-right px-3 py-1.5 rounded-lg text-sm mb-1 transition-colors ${sortBy === o.v ? 'bg-brand-50 text-brand-700 font-semibold' : 'text-slate-600 hover:bg-slate-50'}`}>
                    {o.l}
                  </button>
                ))}
              </div>

              {allTags.length > 0 && (
                <div className="surface p-4">
                  <div className="text-xs font-semibold text-slate-500 uppercase tracking-wide mb-2">תגיות</div>
                  <div className="flex flex-wrap gap-1.5">
                    {tagFilter && (
                      <button onClick={() => setTagFilter(null)} className="text-xs px-2 py-1 rounded-full bg-red-100 text-red-700 font-semibold">
                        ✕ נקה
                      </button>
                    )}
                    {allTags.map(t => (
                      <button key={t} onClick={() => setTagFilter(t)}
                        className={`text-xs px-2 py-1 rounded-full font-semibold transition-colors ${tagFilter === t ? 'bg-brand-600 text-white' : 'bg-slate-100 text-slate-600 hover:bg-brand-100 hover:text-brand-700'}`}>
                        #{t}
                      </button>
                    ))}
                  </div>
                </div>
              )}

              {isModerator && (
                <div className="surface p-4 bg-amber-50/60 border border-amber-200">
                  <label className="flex items-center gap-2 cursor-pointer">
                    <input type="checkbox" checked={showHidden} onChange={e => setShowHidden(e.target.checked)} className="rounded"/>
                    <span className="text-xs">הצג פוסטים מוסתרים</span>
                  </label>
                  <div className="text-[10px] text-amber-700 mt-2">
                    {allPosts.filter(p => p.hidden).length} מוסתרים · {allPosts.filter(p => p.pinned).length} נעוצים
                  </div>
                </div>
              )}
            </aside>

            {/* MAIN */}
            <div className="lg:col-span-3 space-y-3">
              {posts.length === 0 ? (
                <window.EmptyState
                  icon="Sparkles"
                  title={tagFilter ? `אין פוסטים בתגית #${tagFilter}` : channel === 'moderators' ? 'אין פוסטים במנהלים עדיין' : 'אין פוסטים עדיין'}
                  description={channel === 'moderators' ? 'נהל דיון פנימי של הנהלת הקול הקורא' : 'היו הראשונים לשתף'}
                  action={<window.Button variant="primary" icon={<window.Icon.Plus size={16}/>} onClick={() => setNewPostOpen(true)}>פוסט ראשון</window.Button>}
                />
              ) : posts.map(p => (
                <window.PostCard
                  key={p.id}
                  post={p}
                  onOpen={() => setOpenPostId(p.id)}
                  onTagClick={t => setTagFilter(t)}
                />
              ))}
            </div>
          </div>
        </>
      )}

      {tab === 'suppliers' && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {recs.length === 0 ? (
            <div className="md:col-span-3">
              <window.EmptyState icon="Award" title="אין המלצות עדיין"/>
            </div>
          ) : [...recs].sort((a,b) => (b.rating||0) - (a.rating||0)).map(r => {
            const workedWith = (r.authorities || []).map(id => state.authorities.find(a => a.id === id)).filter(Boolean);
            return (
              <div key={r.supplier} className="surface p-5 card-hover animate-fade-in">
                <div className="flex items-start justify-between gap-3 mb-3">
                  <div className="w-12 h-12 rounded-xl bg-gradient-to-br from-amber-400 to-amber-600 text-white flex items-center justify-center font-display font-black text-lg shrink-0">
                    {r.supplier.charAt(0)}
                  </div>
                  <div className="text-left">
                    <div className="flex items-center gap-1">
                      {[1,2,3,4,5].map(n => (
                        <window.Icon.Star key={n} size={14} fill={n <= Math.round(r.rating) ? '#f59e0b' : 'none'} className={n <= Math.round(r.rating) ? 'text-amber-500' : 'text-slate-300'}/>
                      ))}
                    </div>
                    <div className="text-[10px] text-slate-500 mt-0.5 ltr-num">{r.rating.toFixed(1)} · {r.reviews} ביקורות</div>
                  </div>
                </div>
                <h3 className="font-display font-bold text-base">{r.supplier}</h3>
                {r.note && <p className="text-sm text-slate-600 mt-2 italic">"{r.note}"</p>}
                {r.topics?.length > 0 && (
                  <div className="mt-3 flex flex-wrap gap-1">
                    {r.topics.map(t => (
                      <span key={t} className="text-[10px] px-2 py-0.5 rounded-full bg-brand-50 text-brand-700 font-semibold">{t}</span>
                    ))}
                  </div>
                )}
                {workedWith.length > 0 && (
                  <div className="mt-4 pt-3 border-t border-slate-100">
                    <div className="text-[10px] text-slate-500 font-semibold mb-1.5">עבדו איתו:</div>
                    <div className="flex flex-wrap gap-1">
                      {workedWith.map(a => <window.AuthorityChip key={a.id} authority={a} size="xs"/>)}
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}

      <window.NewPostModal open={newPostOpen} onClose={() => setNewPostOpen(false)} defaultChannel={channel}/>
      {openPost && <window.PostDetailModal post={openPost} onClose={() => setOpenPostId(null)}/>}
    </div>
  );
};

// ───────────────────────────────────────────────
//  PostCard — a single post in the feed
// ───────────────────────────────────────────────
window.PostCard = function PostCard({ post: p, onOpen, onTagClick }) {
  const { state, currentUser, likePost, togglePinPost, toggleHidePost, deletePost } = window.useApp();
  const toast = window.useToast();
  const auth = p.authorityId ? state.authorities.find(a => a.id === p.authorityId) : null;
  const author = state.users.find(u => u.id === p.authorId);
  const isHQ = (p.authorRole === 'admin' || p.authorRole === 'national') || (author && (author.role === 'admin' || author.role === 'national'));
  const isModerator = currentUser.role === 'admin' || currentUser.role === 'national';
  const canModerate = isModerator || p.authorId === currentUser.id;
  const images = window.postImages(p);
  const commentCount = (p.commentsList?.length ?? p.comments ?? 0);

  return (
    <article
      className={`surface animate-fade-in overflow-hidden transition-all cursor-pointer hover:shadow-soft-lg hover:-translate-y-0.5 ${p.hidden ? 'opacity-50' : ''} ${p.channel === 'moderators' ? 'ring-1 ring-indigo-200' : ''}`}
      style={p.pinned ? { borderRight: '4px solid #f59e0b' } : undefined}
      onClick={onOpen}
      role="button"
      tabIndex={0}
      onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onOpen(); } }}
      aria-label={`פוסט: ${p.title}`}
    >
      <div className="flex gap-4 p-4">
        {/* Author strip */}
        <div className="w-28 shrink-0 flex flex-col items-center text-center border-l border-slate-100 pl-3">
          <window.Avatar name={author?.name} size={48}/>
          <div className="font-semibold text-xs mt-1.5 truncate w-full">{author?.name}</div>
          {auth ? (
            <div className="mt-1"><window.AuthorityChip authority={auth} size="xs"/></div>
          ) : isHQ ? (
            <span className="mt-1 text-[9px] font-bold px-1.5 py-0.5 rounded-full bg-brand-100 text-brand-700 inline-flex items-center gap-1">
              <window.Icon.Shield size={8}/> הנהלה
            </span>
          ) : null}
          <div className="text-[10px] text-slate-400 mt-1">{window.formatDate(p.date)}</div>
        </div>

        {/* Content */}
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 flex-wrap mb-1">
            {p.pinned && (
              <span className="inline-flex items-center gap-1 text-[10px] font-bold px-1.5 py-0.5 rounded bg-amber-100 text-amber-800">📌 נעוץ</span>
            )}
            {p.channel === 'moderators' && (
              <span className="inline-flex items-center gap-1 text-[10px] font-bold px-1.5 py-0.5 rounded bg-indigo-100 text-indigo-800">🛡 מנהלים</span>
            )}
            {p.hidden && isModerator && (
              <span className="inline-flex items-center gap-1 text-[10px] font-bold px-1.5 py-0.5 rounded bg-red-100 text-red-700">🔒 מוסתר</span>
            )}
            {p.tags?.map(t => (
              <button key={t} onClick={e => { e.stopPropagation(); onTagClick(t); }}
                className="text-[10px] px-2 py-0.5 rounded-full bg-slate-100 text-slate-600 font-semibold hover:bg-brand-100 hover:text-brand-700">
                #{t}
              </button>
            ))}
            {p.editedAt && (
              <span className="text-[10px] text-slate-400 italic" title={`נערך ב-${new Date(p.editedAt).toLocaleString('he-IL')}`}>
                ✎ נערך
              </span>
            )}
          </div>
          <h3 className="font-display font-bold text-base mb-1">{p.title}</h3>
          <p className="text-sm text-slate-700 leading-relaxed whitespace-pre-line line-clamp-3">{p.body}</p>

          <window.PostImages images={images} small/>

          <div className="mt-3 pt-2 border-t border-slate-100 flex items-center justify-between">
            <div className="flex items-center gap-4 text-xs text-slate-500">
              <button onClick={e => { e.stopPropagation(); likePost(p.id); }} className="flex items-center gap-1 hover:text-pink-600 transition-colors focus-visible:ring-2 focus-visible:ring-brand-500 rounded px-1" aria-label="אהבתי">
                <window.Icon.Heart size={14}/>
                <span className="font-semibold">{p.likes || 0}</span>
              </button>
              <button onClick={e => { e.stopPropagation(); onOpen(); }} className="flex items-center gap-1 hover:text-brand-600 transition-colors focus-visible:ring-2 focus-visible:ring-brand-500 rounded px-1" aria-label="פתח תגובות">
                <window.Icon.FileText size={14}/>
                <span>{commentCount} תגובות</span>
              </button>
            </div>
            {canModerate && (
              <div className="flex items-center gap-1" onClick={e => e.stopPropagation()}>
                {p.authorId === currentUser.id && (
                  <button onClick={onOpen} className="p-1.5 rounded-lg text-slate-400 hover:bg-blue-50 hover:text-blue-600" title="ערוך פוסט">
                    <window.Icon.Edit size={13}/>
                  </button>
                )}
                {isModerator && (
                  <>
                    <button onClick={() => { togglePinPost(p.id); toast.push({ message: p.pinned ? 'הוסר נעיצה' : 'הפוסט ננעץ' }); }}
                      className={`p-1.5 rounded-lg ${p.pinned ? 'bg-amber-100 text-amber-700' : 'text-slate-400 hover:bg-amber-50 hover:text-amber-600'}`}
                      title={p.pinned ? 'הסר נעיצה' : 'נעץ פוסט'}>
                      <window.Icon.MapPin size={13}/>
                    </button>
                    <button onClick={() => { toggleHidePost(p.id); toast.push({ message: p.hidden ? 'הפוסט הוצג' : 'הפוסט הוסתר' }); }}
                      className={`p-1.5 rounded-lg ${p.hidden ? 'bg-red-100 text-red-700' : 'text-slate-400 hover:bg-red-50 hover:text-red-600'}`}
                      title={p.hidden ? 'הצג פוסט' : 'הסתר פוסט'}>
                      <window.Icon.Eye size={13}/>
                    </button>
                  </>
                )}
                <button onClick={() => {
                  if (confirm('למחוק פוסט זה לצמיתות?')) { deletePost(p.id); toast.push({ message: 'הפוסט נמחק' }); }
                }} className="p-1.5 rounded-lg text-slate-400 hover:bg-red-50 hover:text-red-600" title="מחיקה">
                  <window.Icon.Trash size={13}/>
                </button>
              </div>
            )}
          </div>
        </div>
      </div>
    </article>
  );
};

// ───────────────────────────────────────────────
//  PostDetailModal — open on click, shows full post + comments + edit
// ───────────────────────────────────────────────
window.PostDetailModal = function PostDetailModal({ post: p, onClose }) {
  const { state, currentUser, editPost, addComment, editComment, deleteComment, likePost } = window.useApp();
  const toast = window.useToast();
  const [editing, setEditing] = uSCM(false);
  const [draft, setDraft] = uSCM({ title: p.title, body: p.body, tags: (p.tags || []).join(', '), images: window.postImages(p) });
  const [newComment, setNewComment] = uSCM('');
  const [editingCommentId, setEditingCommentId] = uSCM(null);
  const [editCommentBody, setEditCommentBody] = uSCM('');

  uECM(() => {
    // Re-sync draft when post updates
    setDraft({ title: p.title, body: p.body, tags: (p.tags || []).join(', '), images: window.postImages(p) });
  }, [p.id, p.editedAt]);

  const author = state.users.find(u => u.id === p.authorId);
  const canEdit = p.authorId === currentUser.id;
  const canModerate = currentUser.role === 'admin' || currentUser.role === 'national';
  const images = window.postImages(p);
  const comments = p.commentsList || [];

  const saveEdit = () => {
    if (!draft.title.trim() || !draft.body.trim()) {
      toast.push({ type: 'error', message: 'כותרת ותוכן נדרשים' });
      return;
    }
    editPost(p.id, {
      title: draft.title.trim(),
      body: draft.body.trim(),
      tags: draft.tags.split(',').map(t => t.trim()).filter(Boolean),
      images: draft.images,
      image: null // clear old single-image field
    });
    toast.push({ type: 'success', message: 'הפוסט עודכן' });
    setEditing(false);
  };

  const submitComment = () => {
    if (!newComment.trim()) return;
    addComment(p.id, newComment.trim());
    setNewComment('');
    toast.push({ type: 'success', message: 'התגובה נוספה' });
  };

  const saveCommentEdit = (commentId) => {
    if (!editCommentBody.trim()) return;
    editComment(p.id, commentId, editCommentBody.trim());
    setEditingCommentId(null);
    toast.push({ type: 'success', message: 'התגובה עודכנה' });
  };

  return (
    <window.Modal
      open={true}
      onClose={onClose}
      size="lg"
      title={
        <div className="flex items-center gap-2">
          <window.Icon.FileText size={20} className="text-brand-600"/>
          <span>{editing ? 'עריכת פוסט' : 'פוסט'}</span>
          {p.channel === 'moderators' && (
            <span className="text-[10px] font-bold px-1.5 py-0.5 rounded bg-indigo-100 text-indigo-800">🛡 מנהלים</span>
          )}
        </div>
      }
      footer={<window.Button variant="outline" onClick={onClose}>סגור</window.Button>}
    >
      {/* Post body */}
      {editing ? (
        <div className="space-y-3">
          <window.Field label="כותרת" required>
            <input value={draft.title} onChange={e => setDraft(d => ({ ...d, title: e.target.value }))} className="input" autoFocus/>
          </window.Field>
          <window.Field label="תוכן" required>
            <textarea value={draft.body} onChange={e => setDraft(d => ({ ...d, body: e.target.value }))} className="textarea" style={{ minHeight: 140 }}/>
          </window.Field>
          <window.Field label="תגיות" help="מופרדות בפסיקים">
            <input value={draft.tags} onChange={e => setDraft(d => ({ ...d, tags: e.target.value }))} className="input"/>
          </window.Field>
          {draft.images.length > 0 && (
            <div>
              <div className="text-xs font-bold text-slate-700 mb-1.5">תמונות ({draft.images.length})</div>
              <div className="grid grid-cols-4 gap-2">
                {draft.images.map((src, i) => (
                  <div key={i} className="relative group">
                    <img src={src} className="w-full aspect-square object-cover rounded-lg bg-slate-100" alt=""/>
                    <button
                      onClick={() => setDraft(d => ({ ...d, images: d.images.filter((_, j) => j !== i) }))}
                      className="absolute top-1 left-1 w-6 h-6 rounded-full bg-red-500 text-white flex items-center justify-center text-xs opacity-0 group-hover:opacity-100 transition-opacity"
                      aria-label="הסר תמונה"
                    >
                      ×
                    </button>
                  </div>
                ))}
              </div>
            </div>
          )}
          <div className="flex items-center justify-end gap-2 pt-2">
            <window.Button variant="outline" onClick={() => setEditing(false)}>ביטול</window.Button>
            <window.Button variant="success" icon={<window.Icon.CheckCircle size={14}/>} onClick={saveEdit}>שמור שינויים</window.Button>
          </div>
        </div>
      ) : (
        <div>
          {/* Meta */}
          <div className="flex items-center gap-3 mb-3 pb-3 border-b border-slate-100">
            <window.Avatar name={author?.name} size={44}/>
            <div className="flex-1">
              <div className="font-bold text-sm">{author?.name}</div>
              <div className="text-[11px] text-slate-500">
                {window.formatDate(p.date)}
                {p.editedAt && (
                  <span className="mr-2 text-slate-400 italic" title={new Date(p.editedAt).toLocaleString('he-IL')}>
                    · ✎ נערך {window.formatDate(p.editedAt)}
                  </span>
                )}
              </div>
            </div>
            {canEdit && (
              <window.Button variant="outline" size="sm" icon={<window.Icon.Edit size={12}/>} onClick={() => setEditing(true)}>ערוך</window.Button>
            )}
          </div>

          {/* Tags + title */}
          {p.tags?.length > 0 && (
            <div className="flex flex-wrap gap-1.5 mb-2">
              {p.tags.map(t => (
                <span key={t} className="text-[10px] px-2 py-0.5 rounded-full bg-slate-100 text-slate-600 font-semibold">#{t}</span>
              ))}
            </div>
          )}
          <h2 className="font-display font-black text-xl mb-2">{p.title}</h2>
          <p className="text-sm text-slate-800 leading-relaxed whitespace-pre-line mb-3">{p.body}</p>

          <window.PostImages images={images}/>

          {/* Reactions */}
          <div className="flex items-center gap-4 mt-4 pt-3 border-t border-slate-100 text-sm">
            <button onClick={() => likePost(p.id)} className="flex items-center gap-1.5 text-slate-600 hover:text-pink-600 transition-colors">
              <window.Icon.Heart size={16}/>
              <span className="font-bold">{p.likes || 0}</span>
            </button>
            <span className="flex items-center gap-1.5 text-slate-600">
              <window.Icon.FileText size={16}/>
              <span>{comments.length} תגובות</span>
            </span>
          </div>
        </div>
      )}

      {/* Comments thread */}
      {!editing && (
        <div className="mt-5">
          <div className="text-xs font-bold uppercase tracking-wider text-slate-500 mb-2">תגובות ({comments.length})</div>
          <div className="space-y-2 max-h-72 overflow-y-auto pr-1">
            {comments.length === 0 && (
              <div className="text-center py-6 text-sm text-slate-400">טרם הוספו תגובות. היו הראשונים.</div>
            )}
            {comments.map(c => {
              const cAuthor = state.users.find(u => u.id === c.authorId);
              const canEditThis = c.authorId === currentUser.id;
              const canDeleteThis = canEditThis || canModerate;
              return (
                <div key={c.id} className="p-3 rounded-lg bg-slate-50 border border-slate-100">
                  <div className="flex items-start gap-2.5">
                    <window.Avatar name={cAuthor?.name} size={28}/>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-1">
                        <div className="font-bold text-xs">{cAuthor?.name || 'משתמש'}</div>
                        <div className="text-[10px] text-slate-400">{new Date(c.date).toLocaleDateString('he-IL')}</div>
                        {c.editedAt && <span className="text-[10px] text-slate-400 italic">· ✎ נערך</span>}
                      </div>
                      {editingCommentId === c.id ? (
                        <div>
                          <textarea value={editCommentBody} onChange={e => setEditCommentBody(e.target.value)} className="textarea text-sm" rows={2} autoFocus/>
                          <div className="flex items-center justify-end gap-1.5 mt-1.5">
                            <button onClick={() => setEditingCommentId(null)} className="text-[11px] text-slate-500 hover:text-slate-900 px-2 py-1 rounded hover:bg-slate-200">ביטול</button>
                            <button onClick={() => saveCommentEdit(c.id)} className="text-[11px] bg-brand-600 text-white font-bold px-3 py-1 rounded hover:bg-brand-700">שמור</button>
                          </div>
                        </div>
                      ) : (
                        <p className="text-sm text-slate-700 whitespace-pre-line">{c.body}</p>
                      )}
                    </div>
                    {editingCommentId !== c.id && (canEditThis || canDeleteThis) && (
                      <div className="flex items-center gap-0.5 shrink-0">
                        {canEditThis && (
                          <button
                            onClick={() => { setEditingCommentId(c.id); setEditCommentBody(c.body); }}
                            className="p-1 text-slate-400 hover:text-blue-600 rounded"
                            title="ערוך תגובה"
                          >
                            <window.Icon.Edit size={12}/>
                          </button>
                        )}
                        {canDeleteThis && (
                          <button
                            onClick={() => {
                              if (confirm('למחוק את התגובה?')) { deleteComment(p.id, c.id); toast.push({ message: 'התגובה נמחקה' }); }
                            }}
                            className="p-1 text-slate-400 hover:text-red-600 rounded"
                            title="מחיקה"
                          >
                            <window.Icon.Trash size={12}/>
                          </button>
                        )}
                      </div>
                    )}
                  </div>
                </div>
              );
            })}
          </div>

          {/* Reply form */}
          <div className="mt-3 pt-3 border-t border-slate-100">
            <div className="flex items-start gap-2">
              <window.Avatar name={currentUser.name} size={32}/>
              <div className="flex-1">
                <textarea
                  value={newComment}
                  onChange={e => setNewComment(e.target.value)}
                  placeholder="הוסף תגובה..."
                  className="textarea text-sm"
                  rows={2}
                  aria-label="תגובה חדשה"
                />
                <div className="flex items-center justify-end mt-1.5">
                  <window.Button variant="primary" size="sm" icon={<window.Icon.Send size={12}/>} onClick={submitComment} disabled={!newComment.trim()}>
                    שלח
                  </window.Button>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </window.Modal>
  );
};

// ───────────────────────────────────────────────
//  NewPostModal — supports multi-image + channel
// ───────────────────────────────────────────────
window.NewPostModal = function NewPostModal({ open, onClose, defaultChannel = 'public' }) {
  const { currentUser, addPost } = window.useApp();
  const toast = window.useToast();
  const [data, setData] = uSCM({ title: '', body: '', tags: '', images: [], channel: defaultChannel });
  const fileRef = uRCM();

  uECM(() => { if (open) setData({ title: '', body: '', tags: '', images: [], channel: defaultChannel }); }, [open, defaultChannel]);

  const isModerator = currentUser.role === 'admin' || currentUser.role === 'national';

  const handleImageFiles = (files) => {
    const arr = Array.from(files || []);
    for (const f of arr) {
      const validation = window.validateFile ? window.validateFile(f, 'image') : { ok: true };
      if (!validation.ok) { toast.push({ type: 'error', title: 'הקובץ נדחה', message: validation.error }); continue; }
      const reader = new FileReader();
      reader.onload = e => setData(d => ({ ...d, images: [...d.images, e.target.result] }));
      reader.readAsDataURL(f);
    }
  };

  const submit = () => {
    if (!data.title.trim() || !data.body.trim()) { toast.push({ type: 'error', message: 'כותרת ותוכן נדרשים' }); return; }
    const authorityId = currentUser.role === 'local' ? currentUser.authorityId : null;
    addPost({
      authorityId,
      authorRole: currentUser.role,
      authorId: currentUser.id,
      title: data.title.trim(),
      body: data.body.trim(),
      tags: data.tags.split(',').map(t => t.trim()).filter(Boolean),
      images: data.images,
      channel: data.channel
    });
    toast.push({ type: 'success', title: 'הפוסט פורסם', message: data.channel === 'moderators' ? 'רק מנהלים יראו את הפוסט' : 'רכזים מכל הרשויות יוכלו לראותו' });
    onClose();
  };

  return (
    <window.Modal
      open={open}
      onClose={onClose}
      title="שיתוף פוסט חדש"
      size="md"
      footer={
        <>
          <window.Button variant="outline" onClick={onClose}>ביטול</window.Button>
          <window.Button variant="primary" icon={<window.Icon.Send size={16}/>} onClick={submit}>פרסום</window.Button>
        </>
      }
    >
      {isModerator && (
        <window.Field label="ערוץ">
          <div className="inline-flex rounded-lg bg-slate-100 p-1">
            <button
              type="button"
              onClick={() => setData(d => ({ ...d, channel: 'public' }))}
              className={`px-3 py-1.5 rounded-md text-sm font-bold transition-colors ${data.channel === 'public' ? 'bg-white shadow-sm text-brand-700' : 'text-slate-600 hover:text-slate-900'}`}
            >
              <window.Icon.FileText size={12} className="inline ml-1"/> כללי
            </button>
            <button
              type="button"
              onClick={() => setData(d => ({ ...d, channel: 'moderators' }))}
              className={`px-3 py-1.5 rounded-md text-sm font-bold transition-colors ${data.channel === 'moderators' ? 'bg-white shadow-sm text-indigo-700' : 'text-slate-600 hover:text-slate-900'}`}
            >
              <window.Icon.Shield size={12} className="inline ml-1"/> מנהלים בלבד
            </button>
          </div>
        </window.Field>
      )}

      <window.Field label="כותרת" required className={isModerator ? 'mt-3' : ''}>
        <input value={data.title} onChange={e => setData(d => ({ ...d, title: e.target.value }))} className="input" placeholder="לדוגמה: סיום מוצלח לסדנת מוגנות" autoFocus/>
      </window.Field>
      <window.Field label="תוכן" required className="mt-3">
        <textarea value={data.body} onChange={e => setData(d => ({ ...d, body: e.target.value }))} className="textarea" style={{ minHeight: 120 }} placeholder="ספר מה קרה, איך זה עבר, המלצות..."/>
      </window.Field>
      <window.Field label="תגיות" help="מופרדות בפסיקים" className="mt-3">
        <input value={data.tags} onChange={e => setData(d => ({ ...d, tags: e.target.value }))} className="input" placeholder="חינוך, בנות, אנגלית"/>
      </window.Field>
      <window.Field label={`תמונות (${data.images.length}/8)`} className="mt-3">
        <div className="grid grid-cols-4 gap-2">
          {data.images.map((src, i) => (
            <div key={i} className="relative group">
              <img src={src} className="w-full aspect-square object-cover rounded-lg bg-slate-100" alt=""/>
              <button
                onClick={() => setData(d => ({ ...d, images: d.images.filter((_, j) => j !== i) }))}
                className="absolute top-1 left-1 w-6 h-6 rounded-full bg-red-500 text-white flex items-center justify-center text-xs"
                aria-label="הסר"
              >×</button>
            </div>
          ))}
          {data.images.length < 8 && (
            <button
              type="button"
              onClick={() => fileRef.current?.click()}
              className="aspect-square rounded-lg border-2 border-dashed border-slate-300 hover:border-brand-400 hover:bg-brand-50 flex flex-col items-center justify-center text-slate-400 hover:text-brand-600 transition-colors"
            >
              <window.Icon.Image size={20}/>
              <span className="text-[10px] mt-1">+ הוסף</span>
            </button>
          )}
        </div>
        <input type="file" ref={fileRef} hidden accept="image/*" multiple onChange={e => { handleImageFiles(e.target.files); e.target.value = ''; }}/>
      </window.Field>
    </window.Modal>
  );
};

// ───────────────────────────────────────────────
//  SupplierReviewModal — unchanged from previous version
// ───────────────────────────────────────────────
window.SupplierReviewModal = function SupplierReviewModal({ open, onClose, supplier, authorityId }) {
  const { addSupplierReview } = window.useApp();
  const toast = window.useToast();
  const [rating, setRating] = uSCM(5);
  const [note, setNote] = uSCM('');

  uECM(() => { if (open) { setRating(5); setNote(''); } }, [open]);

  const submit = () => {
    if (!supplier) return;
    addSupplierReview(supplier, rating, note.trim(), authorityId);
    toast.push({ type: 'success', title: 'תודה!', message: 'הביקורת שלך תעזור לרכזים אחרים' });
    onClose();
  };

  return (
    <window.Modal open={open} onClose={onClose} title={`ביקורת על ${supplier || 'ספק'}`} size="sm"
      footer={<>
        <window.Button variant="outline" onClick={onClose}>ביטול</window.Button>
        <window.Button variant="primary" icon={<window.Icon.Star size={16}/>} onClick={submit}>שלח ביקורת</window.Button>
      </>}>
      <div className="flex items-center gap-1 justify-center mb-4">
        {[1,2,3,4,5].map(n => (
          <button key={n} onClick={() => setRating(n)}>
            <window.Icon.Star size={32} fill={n <= rating ? '#f59e0b' : 'none'} className={n <= rating ? 'text-amber-500' : 'text-slate-300'}/>
          </button>
        ))}
      </div>
      <div className="text-center text-xs text-slate-500 mb-4">
        {rating === 1 && 'לא מרוצה'}
        {rating === 2 && 'חלש'}
        {rating === 3 && 'בסדר'}
        {rating === 4 && 'טוב'}
        {rating === 5 && 'מצוין!'}
      </div>
      <window.Field label="הערה (אופציונלי)">
        <textarea value={note} onChange={e => setNote(e.target.value)} className="textarea" style={{ minHeight: 80 }}
          placeholder="מה היה טוב? מה מומלץ? מה לדעת מראש?"/>
      </window.Field>
    </window.Modal>
  );
};
