// ═══════════════════════════════════════════════════════════════
//  Dashboard Widgets — render saved stats + customize modal
// ═══════════════════════════════════════════════════════════════

const { useState: uSDW, useEffect: uEDW, useMemo: uMDW } = React;

// ───────────────────────────────────────────────
//  Shared filter helper — used by StatBuilder & Widgets
// ───────────────────────────────────────────────
window.applyStatFilter = function(activities, filter, state) {
  let acts = [...activities];
  if (!filter) return acts;

  if (filter.quarter && filter.quarter !== 'all') acts = acts.filter(a => a.quarter === filter.quarter);
  if (filter.cluster && filter.cluster !== 'all') acts = acts.filter(a => a.cluster === filter.cluster);
  if (filter.status && filter.status !== 'all') acts = acts.filter(a => window.deriveStatus(a) === filter.status);

  if (filter.authorities?.length) acts = acts.filter(a => filter.authorities.includes(a.authorityId));
  if (filter.suppliers?.length)   acts = acts.filter(a => filter.suppliers.includes(a.supplierName));

  if (filter.gender && filter.gender !== 'all') acts = acts.filter(a => a.gender === filter.gender);
  if (filter.communityStream && filter.communityStream !== 'all') acts = acts.filter(a => a.communityStream === filter.communityStream);
  if (filter.ageGroup && filter.ageGroup !== 'all') acts = acts.filter(a => a.targetPopulation && a.targetPopulation.includes(filter.ageGroup));

  if (filter.dateFrom) acts = acts.filter(a => (a.startDate || '') >= filter.dateFrom);
  if (filter.dateTo)   acts = acts.filter(a => (a.endDate   || a.startDate || '') <= filter.dateTo);

  if (filter.budgetMin) {
    const min = Number(filter.budgetMin);
    acts = acts.filter(a => ((a.plannedBudget || 0) + (a.plannedCatering || 0) + (a.plannedPublicity || 0)) >= min);
  }
  if (filter.budgetMax) {
    const max = Number(filter.budgetMax);
    acts = acts.filter(a => ((a.plannedBudget || 0) + (a.plannedCatering || 0) + (a.plannedPublicity || 0)) <= max);
  }

  return acts;
};

// ───────────────────────────────────────────────
//  Compute data from a saved stat config
// ───────────────────────────────────────────────
window.computeStatData = function(state, cfg) {
  let acts = window.applyStatFilter(state.activities, cfg.filter, state);

  const groups = {};
  acts.forEach(a => {
    let key, label, color;
    if (cfg.dimension === 'authority') {
      const auth = state.authorities.find(x => x.id === a.authorityId);
      key = auth?.id || '-'; label = auth?.shortName || auth?.name || 'לא ידוע'; color = auth?.color;
    } else if (cfg.dimension === 'cluster') {
      const c = window.clusterById(a.cluster); key = a.cluster; label = c?.shortName || a.cluster; color = c?.color;
    } else if (cfg.dimension === 'quarter') {
      key = a.quarter; label = a.quarter || 'לא הוגדר';
    } else if (cfg.dimension === 'supplier') {
      key = a.supplierName || '-'; label = a.supplierName || 'ללא ספק';
    } else if (cfg.dimension === 'status') {
      const s = window.deriveStatus(a); key = s; label = window.STATUS_META[s]?.label || s;
    } else if (cfg.dimension === 'coordinator') {
      const u = state.users.find(x => x.id === a.coordinatorId); key = u?.id || '-'; label = u?.name || 'לא ידוע';
    }
    if (!groups[key]) groups[key] = { key, name: label, value: 0, color };
    if (cfg.measure === 'count') groups[key].value += 1;
    else if (cfg.measure === 'plannedBudget') groups[key].value += (a.plannedBudget || 0) + (a.plannedCatering || 0) + (a.plannedPublicity || 0);
    else if (cfg.measure === 'actualBudget') groups[key].value += (a.totalActualBudget || 0);
    else if (cfg.measure === 'participants') groups[key].value += (a.actualParticipants || a.plannedParticipants || 0);
    else if (cfg.measure === 'units') groups[key].value += (a.completedUnits || 0);
  });
  return Object.values(groups).sort((a, b) => b.value - a.value);
};

// ───────────────────────────────────────────────
//  Draggable widget wrapper
// ───────────────────────────────────────────────
window.DraggableWidget = function DraggableWidget({ id, onDragStart, onDragOver, onDrop, onDragEnd, isDragging, isDropTarget, children }) {
  return (
    <div
      draggable
      onDragStart={(e) => { e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('text/plain', id); onDragStart?.(id); }}
      onDragOver={(e) => { e.preventDefault(); e.dataTransfer.dropEffect = 'move'; onDragOver?.(id); }}
      onDrop={(e) => { e.preventDefault(); onDrop?.(id); }}
      onDragEnd={() => onDragEnd?.()}
      className={`relative transition-all ${isDragging ? 'opacity-40 scale-95' : ''} ${isDropTarget ? 'ring-2 ring-brand-500 ring-offset-2' : ''}`}
      style={{ cursor: 'grab' }}
    >
      <div className="absolute top-2 right-2 w-7 h-7 rounded-lg bg-white/80 backdrop-blur border border-slate-200 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10 shadow-sm" data-tip="גרור להזזה">
        <window.Icon.MoreVertical size={14} className="text-slate-500"/>
      </div>
      {children}
    </div>
  );
};

// ───────────────────────────────────────────────
//  A single saved-stat widget on the dashboard
// ───────────────────────────────────────────────
window.SavedStatWidget = function SavedStatWidget({ stat, onEdit, onRemove }) {
  const { state } = window.useApp();
  const R = window.Recharts;
  const chartColors = ['#2563eb', '#7c3aed', '#059669', '#d97706', '#dc2626', '#ec4899', '#06b6d4', '#84cc16', '#a855f7', '#f97316'];

  const data = uMDW(() => window.computeStatData(state, stat), [state, stat]);

  const measureLabels = {
    count: 'מספר פעילויות', plannedBudget: 'תקציב מתוכנן', actualBudget: 'תקציב בפועל',
    participants: 'משתתפים', units: 'יחידות הושלמו'
  };
  const isMoney = ['plannedBudget', 'actualBudget'].includes(stat.measure);
  const total = data.reduce((s, d) => s + d.value, 0);

  const formatVal = (v) => isMoney ? `₪ ${v.toLocaleString('he-IL')}` : v.toLocaleString('he-IL');

  return (
    <div className="surface p-5 animate-fade-in relative group" style={{ borderTop: '3px solid #f59e0b' }}>
      <div className="flex items-start justify-between gap-2 mb-3">
        <div className="min-w-0 flex-1">
          <div className="flex items-center gap-1.5 text-[10px] font-bold text-amber-700 uppercase tracking-wide mb-0.5">
            <window.Icon.Star size={10}/>
            סטטיסטיקה שמורה
          </div>
          <h3 className="font-display font-bold text-base truncate">{stat.name}</h3>
          <div className="text-xs text-slate-500">{measureLabels[stat.measure]}</div>
        </div>
        <div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
          <button onClick={onEdit} className="p-1.5 text-slate-500 hover:bg-slate-100 rounded-lg" data-tip="עריכה">
            <window.Icon.Edit size={14}/>
          </button>
          <button onClick={onRemove} className="p-1.5 text-slate-500 hover:bg-red-50 hover:text-red-600 rounded-lg" data-tip="הסרה מהדשבורד">
            <window.Icon.X size={14}/>
          </button>
        </div>
      </div>

      {data.length === 0 ? (
        <div className="py-8 text-center text-sm text-slate-500">אין נתונים</div>
      ) : stat.chartType === 'bar' ? (
        <R.ResponsiveContainer width="100%" height={220}>
          <R.BarChart data={data}>
            <R.CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0"/>
            <R.XAxis dataKey="name" tick={{ fontSize: 10, fill: '#64748b' }}/>
            <R.YAxis tick={{ fontSize: 10, fill: '#64748b' }} tickFormatter={v => isMoney ? (v >= 1000 ? (v/1000).toFixed(0) + 'K' : v) : v}/>
            <R.Tooltip formatter={v => formatVal(v)} contentStyle={{ borderRadius: 10, border: '1px solid #e2e8f0', fontSize: 12 }}/>
            <R.Bar dataKey="value" radius={[6, 6, 0, 0]}>
              {data.map((g, i) => <R.Cell key={i} fill={g.color || chartColors[i % chartColors.length]}/>)}
            </R.Bar>
          </R.BarChart>
        </R.ResponsiveContainer>
      ) : stat.chartType === 'pie' ? (
        <R.ResponsiveContainer width="100%" height={220}>
          <R.PieChart>
            <R.Pie data={data} dataKey="value" innerRadius={45} outerRadius={80} paddingAngle={2}>
              {data.map((g, i) => <R.Cell key={i} fill={g.color || chartColors[i % chartColors.length]}/>)}
            </R.Pie>
            <R.Tooltip formatter={v => formatVal(v)} contentStyle={{ borderRadius: 10, border: '1px solid #e2e8f0', fontSize: 12 }}/>
            <R.Legend wrapperStyle={{ fontSize: 10 }}/>
          </R.PieChart>
        </R.ResponsiveContainer>
      ) : stat.chartType === 'line' ? (
        <R.ResponsiveContainer width="100%" height={220}>
          <R.LineChart data={data}>
            <R.CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0"/>
            <R.XAxis dataKey="name" tick={{ fontSize: 10, fill: '#64748b' }}/>
            <R.YAxis tick={{ fontSize: 10, fill: '#64748b' }} tickFormatter={v => isMoney ? (v >= 1000 ? (v/1000).toFixed(0) + 'K' : v) : v}/>
            <R.Tooltip formatter={v => formatVal(v)} contentStyle={{ borderRadius: 10, border: '1px solid #e2e8f0', fontSize: 12 }}/>
            <R.Line type="monotone" dataKey="value" stroke="#2563eb" strokeWidth={3} dot={{ r: 4, fill: '#2563eb' }}/>
          </R.LineChart>
        </R.ResponsiveContainer>
      ) : (
        <div className="space-y-1.5 max-h-48 overflow-y-auto">
          {data.slice(0, 8).map((g, i) => {
            const pct = total ? g.value / total * 100 : 0;
            return (
              <div key={g.key} className="flex items-center gap-2 text-xs">
                <div className="w-2.5 h-2.5 rounded-full shrink-0" style={{ background: g.color || chartColors[i % chartColors.length] }}/>
                <span className="flex-1 truncate font-medium">{g.name}</span>
                <span className="font-bold ltr-num">{formatVal(g.value)}</span>
                <span className="text-slate-400 text-[10px] w-10 text-left">{pct.toFixed(0)}%</span>
              </div>
            );
          })}
        </div>
      )}

      <div className="mt-3 pt-3 border-t border-slate-100 text-xs text-slate-500 flex items-center justify-between">
        <span>סה"כ <strong className="text-slate-800 ltr-num">{formatVal(total)}</strong></span>
        <span className="text-[10px]">{data.length} קבוצות</span>
      </div>
    </div>
  );
};

// ───────────────────────────────────────────────
//  Draggable Widget Grid — renders + reorders pinned stats
// ───────────────────────────────────────────────
window.DraggableWidgetGrid = function DraggableWidgetGrid({ stats }) {
  const { state, setWidgetOrder, updateSavedStat } = window.useApp();
  const { navigate } = window.useRouter();
  const [draggedId, setDraggedId] = uSDW(null);
  const [dropTargetId, setDropTargetId] = uSDW(null);

  // Compute order: saved order first, then new stats at end
  const orderedStats = uMDW(() => {
    const saved = state.dashboardConfig?.widgetOrder || [];
    const map = new Map(stats.map(s => [s.id, s]));
    const ordered = [];
    saved.forEach(id => { if (map.has(id)) { ordered.push(map.get(id)); map.delete(id); }});
    return [...ordered, ...Array.from(map.values())];
  }, [stats, state.dashboardConfig?.widgetOrder]);

  const onDragStart = (id) => setDraggedId(id);
  const onDragOver = (id) => { if (id !== draggedId) setDropTargetId(id); };
  const onDragEnd = () => { setDraggedId(null); setDropTargetId(null); };
  const onDrop = (targetId) => {
    if (!draggedId || draggedId === targetId) return;
    const ids = orderedStats.map(s => s.id);
    const fromIdx = ids.indexOf(draggedId);
    const toIdx = ids.indexOf(targetId);
    if (fromIdx < 0 || toIdx < 0) return;
    ids.splice(fromIdx, 1);
    ids.splice(toIdx, 0, draggedId);
    setWidgetOrder(ids);
    setDraggedId(null);
    setDropTargetId(null);
  };

  return (
    <div className="mb-6 animate-fade-in">
      <div className="flex items-center justify-between mb-3">
        <div className="flex items-center gap-2">
          <window.Icon.Star size={14} className="text-amber-500"/>
          <h3 className="font-display font-bold text-sm">סטטיסטיקות שמורות</h3>
          <span className="text-xs text-slate-500">· גרור כדי לסדר מחדש</span>
        </div>
      </div>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
        {orderedStats.map(st => (
          <div key={st.id} className="group"
               draggable
               onDragStart={(e) => { e.dataTransfer.effectAllowed = 'move'; onDragStart(st.id); }}
               onDragOver={(e) => { e.preventDefault(); onDragOver(st.id); }}
               onDrop={(e) => { e.preventDefault(); onDrop(st.id); }}
               onDragEnd={onDragEnd}
               style={{ cursor: draggedId === st.id ? 'grabbing' : 'grab' }}>
            <div className={`relative transition-all ${draggedId === st.id ? 'opacity-40 scale-95' : ''} ${dropTargetId === st.id && draggedId !== st.id ? 'ring-2 ring-brand-500 ring-offset-2 scale-[1.02]' : ''}`}>
              <div className="absolute top-2 right-2 w-7 h-7 rounded-lg bg-white shadow-md border border-slate-200 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity z-10" data-tip="גרור לסידור">
                <window.Icon.MoreVertical size={14} className="text-slate-500"/>
              </div>
              <window.SavedStatWidget
                stat={st}
                onEdit={() => navigate('stats', { initial: st })}
                onRemove={() => updateSavedStat(st.id, { pinnedToDashboard: false })}
              />
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

// ───────────────────────────────────────────────
//  Default Widgets Registry — shared across dashboard + stat builder
// ───────────────────────────────────────────────
window.DEFAULT_WIDGETS = [
  { id: 'kpis',              label: 'כרטיסי KPI ראשיים',       description: 'תקציב, מתוכנן, בפועל, שולם', icon: 'Coins' },
  { id: 'attention',         label: 'פעולות דרושות',             description: 'ממתינים לאישור, מוכנים לתשלום', icon: 'AlertCircle' },
  { id: 'cluster-chart',     label: 'ניצול תקציב לפי אשכול', description: 'גרף השוואת מתוכנן/בפועל', icon: 'BarChart' },
  { id: 'status-pie',        label: 'פילוח סטטוס פעילויות',      description: 'תרשים עוגה של מצבי הפעילות', icon: 'PieChart' },
  { id: 'authorities-table', label: 'טבלת רשויות',                description: 'ניצול תקציב לפי רשות', icon: 'Building' },
  { id: 'recent-activity',   label: 'פעילות אחרונה',              description: '6 הפעילויות האחרונות', icon: 'Activity' }
];

// ───────────────────────────────────────────────
//  Customize Dashboard — Bottom Sheet
// ───────────────────────────────────────────────
window.CustomizeDashboardSheet = function CustomizeDashboardSheet({ open, onClose }) {
  const { state, currentUser, toggleDashboardWidget, deleteSavedStat, updateSavedStat, setState } = window.useApp();
  const toast = window.useToast();

  const hidden = new Set((state.dashboardConfig?.hiddenDefaults) || []);
  const savedStats = state.savedStats || [];
  const canEditStats = currentUser.role !== 'local';

  uEDW(() => {
    if (!open) return;
    const scrollY = window.scrollY;
    document.body.style.top = `-${scrollY}px`;
    document.body.classList.add('modal-open');
    return () => {
      document.body.classList.remove('modal-open');
      document.body.style.top = '';
      window.scrollTo(0, scrollY);
    };
  }, [open]);

  if (!open) return null;

  const resetToDefaults = () => {
    if (!confirm('לאפס את כל ההגדרות למצב ברירת המחדל? כל הסטטיסטיקות השמורות יימחקו.')) return;
    setState(s => ({
      ...s,
      savedStats: [],
      dashboardConfig: { hiddenDefaults: [], widgetOrder: [] }
    }));
    toast.push({ type: 'success', message: 'הוחזר למצב ברירת מחדל' });
    onClose();
  };

  return ReactDOM.createPortal(
    <div className="modal-overlay" onClick={onClose}>
      <div
        onClick={e => e.stopPropagation()}
        className="bg-white rounded-2xl shadow-2xl animate-fade-in w-full"
        style={{ maxWidth: '900px', maxHeight: '85vh', display: 'flex', flexDirection: 'column' }}
      >
        {/* Header */}
        <div className="px-6 py-4 flex items-center justify-between border-b border-slate-100 bg-white z-10 rounded-t-2xl">
          <div>
            <h2 className="font-display font-black text-xl">התאמה אישית של הדשבורד</h2>
            <p className="text-xs text-slate-500 mt-0.5">הצג, הסתר או גרור כדי לסדר</p>
          </div>
          <div className="flex items-center gap-2">
            <window.Button variant="outline" size="sm" icon={<window.Icon.ArrowRight size={14}/>} onClick={resetToDefaults}>
              איפוס ברירת מחדל
            </window.Button>
            <button onClick={onClose} className="w-9 h-9 rounded-lg hover:bg-slate-100 flex items-center justify-center text-slate-500">
              <window.Icon.X size={18}/>
            </button>
          </div>
        </div>

        {/* Content */}
        <div className="p-6 grid grid-cols-1 md:grid-cols-2 gap-6 overflow-y-auto flex-1">
          {/* Default widgets */}
          <div>
            <div className="flex items-center gap-2 mb-3">
              <window.Icon.Layers size={16} className="text-brand-600"/>
              <h3 className="font-display font-bold text-sm">ווידג'טים קבועים</h3>
              <span className="text-[10px] text-slate-400">· {window.DEFAULT_WIDGETS.filter(w => !hidden.has(w.id)).length} מוצגים</span>
            </div>
            <div className="space-y-2">
              {window.DEFAULT_WIDGETS.map(w => {
                const on = !hidden.has(w.id);
                const IconC = window.Icon[w.icon] || window.Icon.Layers;
                return (
                  <label key={w.id} className={`flex items-center gap-3 p-3 rounded-xl border cursor-pointer transition-all ${on ? 'border-emerald-300 bg-emerald-50/70' : 'border-slate-200 bg-white'}`}>
                    <input type="checkbox" checked={on} onChange={() => toggleDashboardWidget(w.id)} className="w-4 h-4 accent-emerald-600"/>
                    <div className={`w-8 h-8 rounded-lg flex items-center justify-center shrink-0 ${on ? 'bg-emerald-100 text-emerald-700' : 'bg-slate-100 text-slate-500'}`}>
                      <IconC size={14}/>
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="font-semibold text-sm">{w.label}</div>
                      <div className="text-[11px] text-slate-500 truncate">{w.description}</div>
                    </div>
                  </label>
                );
              })}
            </div>
          </div>

          {/* Saved stats */}
          <div>
            <div className="flex items-center gap-2 mb-3">
              <window.Icon.Star size={16} className="text-amber-500"/>
              <h3 className="font-display font-bold text-sm">סטטיסטיקות שמורות</h3>
              <span className="text-[10px] text-slate-400">· {savedStats.length}</span>
            </div>
            {savedStats.length === 0 ? (
              <div className="p-5 rounded-xl bg-gradient-to-br from-amber-50 to-yellow-50 border border-amber-200 text-center">
                <window.Icon.Sparkles size={24} className="mx-auto text-amber-500 mb-2"/>
                <div className="text-sm font-semibold text-amber-900 mb-1">עדיין אין סטטיסטיקות שמורות</div>
                <div className="text-[11px] text-amber-800">צור סטטיסטיקות מותאמות אישית בבונה סטטיסטיקות</div>
              </div>
            ) : (
              <div className="space-y-2">
                {savedStats.map(st => {
                  const on = st.pinnedToDashboard !== false;
                  return (
                    <div key={st.id} className={`flex items-center gap-3 p-3 rounded-xl border transition-all ${on ? 'border-amber-300 bg-amber-50/70' : 'border-slate-200 bg-white'}`}>
                      <input type="checkbox" checked={on} onChange={() => updateSavedStat(st.id, { pinnedToDashboard: !on })} className="w-4 h-4 accent-amber-600"/>
                      <div className="w-8 h-8 rounded-lg bg-amber-100 text-amber-700 flex items-center justify-center shrink-0">
                        <window.Icon.Star size={14}/>
                      </div>
                      <div className="flex-1 min-w-0">
                        <div className="font-semibold text-sm truncate">{st.name}</div>
                        <div className="text-[11px] text-slate-500">{st.chartType} · {st.dimension}</div>
                      </div>
                      {canEditStats && (
                        <button onClick={() => {
                          if (confirm(`למחוק "${st.name}"?`)) { deleteSavedStat(st.id); toast.push({ message: 'נמחק' }); }
                        }} className="p-1.5 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-lg">
                          <window.Icon.Trash size={14}/>
                        </button>
                      )}
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>,
    document.body
  );
};

// Keep old name as alias for compatibility
window.CustomizeDashboardModal = window.CustomizeDashboardSheet;
