// ═══════════════════════════════════════════════════════════════
//  Resources Page (שימושון) — downloadable templates + resources
// ═══════════════════════════════════════════════════════════════

const { useState: uSR, useEffect: uER, useRef: uRR } = React;

// Default resource categories
window.DEFAULT_RESOURCES = [
  {
    id: 'logos', category: 'logos',
    label: 'לוגואים של הרשות החרדית',
    icon: 'Image', color: '#2563eb',
    description: 'לוגואים בפורמטים שונים לשימוש בפרסומים'
  },
  {
    id: 'publications', category: 'publications',
    label: 'תבניות פרסום',
    icon: 'Image', color: '#7c3aed',
    description: 'תבניות רולאפים, פליירים ומודעות'
  },
  {
    id: 'forms', category: 'forms',
    label: 'טפסים ריקים',
    icon: 'FileText', color: '#059669',
    description: 'בלאנקים לדרישת תשלום, דו"ח 66 ועוד'
  },
  {
    id: 'guides', category: 'guides',
    label: 'מדריכים והנחיות',
    icon: 'Lightbulb', color: '#d97706',
    description: 'מדריכי שימוש והנחיות מקצועיות'
  },
  {
    id: 'agreements', category: 'agreements',
    label: 'הסכמים ומסמכים רשמיים',
    icon: 'Shield', color: '#64748b',
    description: 'הסכם קול קורא, נספחים חוזיים'
  }
];

window.ResourcesPage = function ResourcesPage() {
  const { state, setState, currentUser } = window.useApp();
  const toast = window.useToast();
  const [uploadCategory, setUploadCategory] = uSR(null);
  const fileRef = uRR();

  const isAdmin = currentUser.role === 'admin';
  const resources = state.resources || [];

  const handleUpload = (file, category) => {
    if (!file) return;
    const reader = new FileReader();
    reader.onload = e => {
      const resource = {
        id: window.uid(),
        name: file.name,
        category,
        type: window.getFileType ? window.getFileType(file.name) : 'file',
        data: e.target.result,
        size: file.size,
        uploadedAt: new Date().toISOString().slice(0, 10),
        uploadedBy: currentUser.id
      };
      setState(s => ({ ...s, resources: [...(s.resources || []), resource] }));
      toast.push({ type: 'success', title: 'הקובץ הועלה', message: file.name });
    };
    reader.readAsDataURL(file);
  };

  const handleDownload = (resource) => {
    const link = document.createElement('a');
    link.href = resource.data;
    link.download = resource.name;
    link.click();
  };

  const handleDelete = (id, name) => {
    if (!confirm(`למחוק את "${name}"?`)) return;
    setState(s => ({ ...s, resources: (s.resources || []).filter(r => r.id !== id) }));
    toast.push({ message: 'נמחק' });
  };

  return (
    <div className="animate-fade-in">
      <window.PageHeader
        title="שימושון"
        subtitle="קבצים שימושיים לרכזים — לוגואים, תבניות פרסום, טפסים ריקים, מדריכים והסכמים"
      />

      <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
        {window.DEFAULT_RESOURCES.map(cat => {
          const items = resources.filter(r => r.category === cat.category);
          const Icon = window.Icon[cat.icon] || window.Icon.File;
          return (
            <div key={cat.id} className="surface overflow-hidden">
              <div className="p-4 flex items-center gap-3 border-b border-slate-100" style={{ background: cat.color + '08' }}>
                <div className="w-10 h-10 rounded-lg flex items-center justify-center text-white shrink-0" style={{ background: cat.color }}>
                  <Icon size={18}/>
                </div>
                <div className="flex-1 min-w-0">
                  <h3 className="font-display font-bold">{cat.label}</h3>
                  <p className="text-xs text-slate-500">{cat.description}</p>
                </div>
                {isAdmin && (
                  <window.Button variant="outline" size="sm" icon={<window.Icon.Plus size={14}/>}
                    onClick={() => { setUploadCategory(cat.category); fileRef.current?.click(); }}>
                    העלאה
                  </window.Button>
                )}
              </div>

              <div className="p-3">
                {items.length === 0 ? (
                  <div className="py-8 text-center">
                    <Icon size={28} className="mx-auto opacity-30 mb-2 text-slate-400"/>
                    <div className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-amber-50 border border-amber-200 text-amber-800 text-xs font-bold">
                      <window.Icon.Clock size={12}/>
                      יעודכן בהמשך
                    </div>
                    {isAdmin && <div className="text-[11px] mt-2 text-slate-500">לחץ "העלאה" להוסיף קובץ ראשון</div>}
                  </div>
                ) : (
                  <div className="space-y-1.5">
                    {items.map(item => (
                      <div key={item.id} className="group flex items-center gap-3 p-2.5 rounded-lg hover:bg-slate-50 border border-slate-100">
                        {item.type === 'image' && item.data ? (
                          <img src={item.data} className="w-10 h-10 rounded object-cover shrink-0"/>
                        ) : (
                          <div className="w-10 h-10 rounded-lg flex items-center justify-center text-white text-[9px] font-bold shrink-0" style={{ background: cat.color }}>
                            {(item.type || 'FILE').toUpperCase().slice(0, 4)}
                          </div>
                        )}
                        <div className="flex-1 min-w-0">
                          <div className="text-sm font-semibold truncate">{item.name}</div>
                          <div className="text-[10px] text-slate-500">
                            {item.size ? `${(item.size / 1024).toFixed(1)} KB · ` : ''}
                            {window.formatDate(item.uploadedAt)}
                          </div>
                        </div>
                        <button onClick={() => handleDownload(item)} className="p-1.5 text-slate-500 hover:bg-white hover:text-brand-700 rounded-lg" data-tip="הורדה">
                          <window.Icon.Download size={14}/>
                        </button>
                        {isAdmin && (
                          <button onClick={() => handleDelete(item.id, item.name)} className="p-1.5 text-slate-400 hover:bg-red-50 hover:text-red-600 rounded-lg opacity-0 group-hover:opacity-100 transition-opacity" data-tip="מחיקה">
                            <window.Icon.Trash size={14}/>
                          </button>
                        )}
                      </div>
                    ))}
                  </div>
                )}
              </div>
            </div>
          );
        })}
      </div>

      <input type="file" ref={fileRef} hidden
        onChange={e => { if (e.target.files[0]) { handleUpload(e.target.files[0], uploadCategory); e.target.value = ''; } }}/>

      {/* Admin tip */}
      {isAdmin && (
        <div className="mt-5 p-4 rounded-xl bg-gradient-to-br from-amber-50 to-yellow-50 border border-amber-200">
          <div className="flex items-start gap-3">
            <div className="w-10 h-10 rounded-xl bg-amber-500 text-white flex items-center justify-center shrink-0">
              <window.Icon.Info size={18}/>
            </div>
            <div>
              <div className="font-display font-bold text-sm text-amber-900 mb-1">ניהול השימושון</div>
              <div className="text-xs text-amber-800 leading-relaxed">
                העלה קבצי תבניות (Word, PDF, PNG) שהרכזים המקומיים והארציים יוכלו להוריד.
                הקבצים נשמרים בדפדפן ויתקיימו לאורך זמן. מומלץ להעלות: לוגו הרשות החרדית ברזולוציות שונות, תבנית רולאפ, פליירים, טפסים ריקים, מדריכי שימוש.
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};
