// ═══════════════════════════════════════════════════════════════
//  Custom Statistics Builder
// ═══════════════════════════════════════════════════════════════

const { useState: uSSB, useEffect: uESB, useMemo: uMSB } = React;

window.StatBuilderPage = function StatBuilderPage({ initial }) {
  const { state, saveStat, deleteSavedStat, updateSavedStat } = window.useApp();
  const toast = window.useToast();
  const R = window.Recharts;

  const [dimension, setDimension] = uSSB(initial?.dimension || 'authority');
  const [measure, setMeasure] = uSSB(initial?.measure || 'actualBudget');
  const [chartType, setChartType] = uSSB(initial?.chartType || 'bar');
  const [filter, setFilter] = uSSB(initial?.filter || {
    quarter: 'all', cluster: 'all', status: 'all',
    authorities: [], suppliers: [], gender: 'all', communityStream: 'all',
    dateFrom: '', dateTo: '', budgetMin: '', budgetMax: ''
  });
  const [showAdvanced, setShowAdvanced] = uSSB(false);
  const [saveOpen, setSaveOpen] = uSSB(false);
  const [saveName, setSaveName] = uSSB('');
  const [pinToDashboard, setPinToDashboard] = uSSB(true);
  const [editingId, setEditingId] = uSSB(initial?.id || null);

  const dimensions = [
    { id: 'authority',   label: 'לפי רשות',       icon: 'Building' },
    { id: 'cluster',     label: 'לפי אשכול',      icon: 'Layers' },
    { id: 'quarter',     label: 'לפי רבעון',      icon: 'Calendar' },
    { id: 'supplier',    label: 'לפי ספק',         icon: 'Briefcase' },
    { id: 'status',      label: 'לפי סטטוס',       icon: 'Activity' },
    { id: 'coordinator', label: 'לפי רכז מקומי',   icon: 'Users' }
  ];

  const measures = [
    { id: 'count',         label: 'מספר פעילויות',    unit: '' },
    { id: 'plannedBudget', label: 'תקציב מתוכנן',     unit: '₪' },
    { id: 'actualBudget',  label: 'תקציב בפועל',      unit: '₪' },
    { id: 'participants',  label: 'משתתפים',           unit: '' },
    { id: 'units',         label: 'יחידות הושלמו',     unit: '' }
  ];

  const chartTypes = [
    { id: 'bar',  label: 'עמודות', icon: 'BarChart' },
    { id: 'pie',  label: 'עוגה',    icon: 'PieChart' },
    { id: 'line', label: 'קו',      icon: 'TrendingUp' },
    { id: 'table',label: 'טבלה',   icon: 'Programs' }
  ];

  // Filter activities using shared helper (keeps dashboard widgets in sync)
  const activities = window.applyStatFilter(state.activities, filter, state);

  const quarters = [...new Set(state.activities.map(a => a.quarter).filter(Boolean))].sort();
  const suppliers = [...new Set(state.activities.map(a => a.supplierName).filter(Boolean))].sort();
  const activeFilterCount = [
    filter.quarter !== 'all', filter.cluster !== 'all', filter.status !== 'all',
    (filter.authorities || []).length > 0, (filter.suppliers || []).length > 0,
    filter.gender && filter.gender !== 'all',
    filter.communityStream && filter.communityStream !== 'all',
    filter.dateFrom, filter.dateTo, filter.budgetMin, filter.budgetMax
  ].filter(Boolean).length;

  // Group by dimension
  const groupedData = uMSB(() => {
    const groups = {};
    activities.forEach(a => {
      let key, label, color;
      if (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 (dimension === 'cluster') {
        const c = window.clusterById(a.cluster);
        key = a.cluster; label = c?.shortName || a.cluster; color = c?.color;
      } else if (dimension === 'quarter') {
        key = a.quarter; label = a.quarter || 'לא הוגדר';
      } else if (dimension === 'supplier') {
        key = a.supplierName || '-'; label = a.supplierName || 'ללא ספק';
      } else if (dimension === 'status') {
        const s = window.deriveStatus(a);
        key = s; label = window.STATUS_META[s]?.label || s;
      } else if (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 (measure === 'count') groups[key].value += 1;
      else if (measure === 'plannedBudget') groups[key].value += (a.plannedBudget || 0) + (a.plannedCatering || 0) + (a.plannedPublicity || 0);
      else if (measure === 'actualBudget') groups[key].value += (a.totalActualBudget || 0);
      else if (measure === 'participants') groups[key].value += (a.actualParticipants || a.plannedParticipants || 0);
      else if (measure === 'units') groups[key].value += (a.completedUnits || 0);
    });
    return Object.values(groups).sort((a, b) => b.value - a.value);
  }, [activities, dimension, measure, state]);

  const currentMeasure = measures.find(m => m.id === measure);
  const totalValue = groupedData.reduce((s, g) => s + g.value, 0);

  const chartColors = ['#2563eb', '#7c3aed', '#059669', '#d97706', '#dc2626', '#ec4899', '#06b6d4', '#84cc16', '#a855f7', '#f97316'];

  return (
    <div className="animate-fade-in">
      <window.PageHeader
        title="בונה סטטיסטיקות"
        subtitle="יצירת גרפים וניתוחים בהתאמה אישית · פיצול לפי רשות, רבעון, ספק, אשכול ועוד"
        actions={
          <>
            <window.Button variant="outline" icon={<window.Icon.Download size={16}/>} onClick={() => {
              const csv = ['קבוצה,ערך', ...groupedData.map(g => `"${g.name}",${g.value}`)].join('\n');
              const blob = new Blob(['\ufeff' + csv], { type: 'text/csv;charset=utf-8;' });
              const link = document.createElement('a');
              link.href = URL.createObjectURL(blob);
              link.download = `סטטיסטיקה-${dimension}-${measure}.csv`;
              link.click();
            }}>
              ייצוא CSV
            </window.Button>
            <window.Button variant="success" icon={<window.Icon.Star size={16}/>} onClick={() => { setSaveName(''); setSaveOpen(true); }}>
              שמירה ב{editingId ? 'עדכון' : 'דשבורד'}
            </window.Button>
          </>
        }
      />

      {/* Save Dialog */}
      <window.Modal
        open={saveOpen}
        onClose={() => setSaveOpen(false)}
        title={editingId ? 'עדכון סטטיסטיקה שמורה' : 'שמירת סטטיסטיקה לדשבורד'}
        size="sm"
        footer={
          <>
            <window.Button variant="outline" onClick={() => setSaveOpen(false)}>ביטול</window.Button>
            <window.Button variant="success" icon={<window.Icon.Star size={16}/>} onClick={() => {
              if (!saveName.trim()) { toast.push({ type: 'error', message: 'נא לתת שם' }); return; }
              if (editingId) {
                updateSavedStat(editingId, {
                  name: saveName.trim(), dimension, measure, chartType, filter, pinnedToDashboard: pinToDashboard
                });
                toast.push({ type: 'success', title: 'עודכן', message: saveName });
              } else {
                saveStat({
                  name: saveName.trim(), dimension, measure, chartType, filter, pinnedToDashboard: pinToDashboard
                });
                toast.push({ type: 'success', title: 'נשמר בדשבורד', message: saveName });
              }
              setSaveOpen(false);
            }}>{editingId ? 'עדכן' : 'שמור'}</window.Button>
          </>
        }
      >
        <window.Field label="שם הסטטיסטיקה" required>
          <input value={saveName} onChange={e => setSaveName(e.target.value)} className="input"
            placeholder="לדוגמה: תקציב לפי רשות — Q1 2026" autoFocus
            onKeyDown={e => { if (e.key === 'Enter') { document.activeElement.blur(); } }}/>
        </window.Field>
        <div className="mt-4 p-3 rounded-xl bg-brand-50 border border-brand-100 flex items-start gap-2">
          <window.Icon.Info size={16} className="text-brand-600 mt-0.5 shrink-0"/>
          <div className="flex-1">
            <label className="flex items-center gap-2 cursor-pointer">
              <input type="checkbox" checked={pinToDashboard} onChange={e => setPinToDashboard(e.target.checked)} className="w-4 h-4 accent-brand-600"/>
              <span className="text-sm font-semibold">הצמדה ללוח הבקרה</span>
            </label>
            <div className="text-xs text-slate-600 mt-1">הסטטיסטיקה תופיע בדשבורד הראשי ותתעדכן בזמן אמת</div>
          </div>
        </div>
        <div className="mt-3 p-3 rounded-xl bg-slate-50 text-xs text-slate-600">
          <strong>הגדרות נוכחיות:</strong>
          <div className="mt-1">פיצול לפי: <strong>{dimensions.find(d=>d.id===dimension)?.label}</strong></div>
          <div>מדד: <strong>{measures.find(m=>m.id===measure)?.label}</strong></div>
          <div>תצוגה: <strong>{chartTypes.find(t=>t.id===chartType)?.label}</strong></div>
        </div>
      </window.Modal>

      {/* Saved stats list */}
      {(state.savedStats || []).length > 0 && (
        <div className="mb-5 surface p-4">
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-2">
              <window.Icon.Star size={16} 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="flex flex-wrap gap-2">
            {(state.savedStats || []).map(st => (
              <div key={st.id} className="flex items-center gap-1 group">
                <button onClick={() => {
                  setDimension(st.dimension); setMeasure(st.measure);
                  setChartType(st.chartType); setFilter(st.filter);
                  setEditingId(st.id); setSaveName(st.name);
                  toast.push({ message: `נטען: ${st.name}` });
                }} className={`px-3 py-1.5 rounded-lg text-xs font-semibold flex items-center gap-1.5 transition-all ${editingId === st.id ? 'bg-amber-500 text-white' : 'bg-amber-50 text-amber-800 border border-amber-200 hover:bg-amber-100'}`}>
                  {st.pinnedToDashboard && <window.Icon.Zap size={11}/>}
                  {st.name}
                </button>
                <button onClick={() => {
                  if (confirm(`למחוק "${st.name}"?`)) {
                    deleteSavedStat(st.id);
                    if (editingId === st.id) { setEditingId(null); setSaveName(''); }
                    toast.push({ message: 'נמחק' });
                  }
                }} className="opacity-0 group-hover:opacity-100 transition-opacity text-slate-400 hover:text-red-600 text-xs">
                  <window.Icon.X size={12}/>
                </button>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Configuration */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-5 mb-5">
        {/* Dimension */}
        <div className="surface p-4">
          <div className="text-xs font-semibold text-slate-500 uppercase tracking-wide mb-3">1. פיצול לפי</div>
          <div className="grid grid-cols-2 gap-2">
            {dimensions.map(d => {
              const Icon = window.Icon[d.icon];
              const on = dimension === d.id;
              return (
                <button key={d.id} onClick={() => setDimension(d.id)}
                  className={`p-3 rounded-xl border-2 flex flex-col items-center gap-1.5 transition-all ${on ? 'border-brand-500 bg-brand-50 text-brand-700' : 'border-slate-200 hover:border-brand-300 text-slate-600'}`}>
                  <Icon size={18}/>
                  <span className="text-xs font-semibold">{d.label}</span>
                </button>
              );
            })}
          </div>
        </div>

        {/* Measure */}
        <div className="surface p-4">
          <div className="text-xs font-semibold text-slate-500 uppercase tracking-wide mb-3">2. מדד</div>
          <div className="space-y-2">
            {measures.map(m => {
              const on = measure === m.id;
              return (
                <button key={m.id} onClick={() => setMeasure(m.id)}
                  className={`w-full p-2.5 rounded-lg border flex items-center justify-between transition-all ${on ? 'border-emerald-500 bg-emerald-50 text-emerald-700' : 'border-slate-200 hover:border-emerald-300 text-slate-600'}`}>
                  <span className="text-sm font-semibold">{m.label}</span>
                  {on && <window.Icon.Check size={14}/>}
                </button>
              );
            })}
          </div>
        </div>

        {/* Chart type + filters */}
        <div className="surface p-4">
          <div className="text-xs font-semibold text-slate-500 uppercase tracking-wide mb-3">3. תצוגה</div>
          <div className="grid grid-cols-4 gap-2 mb-4">
            {chartTypes.map(t => {
              const Icon = window.Icon[t.icon];
              const on = chartType === t.id;
              return (
                <button key={t.id} onClick={() => setChartType(t.id)}
                  className={`p-2.5 rounded-lg border-2 flex flex-col items-center gap-1 transition-all ${on ? 'border-amber-500 bg-amber-50 text-amber-700' : 'border-slate-200 hover:border-amber-300 text-slate-600'}`}>
                  <Icon size={16}/>
                  <span className="text-[10px] font-semibold">{t.label}</span>
                </button>
              );
            })}
          </div>

          <div className="space-y-2">
            <div>
              <label className="text-[10px] font-semibold text-slate-500 uppercase">רבעון</label>
              <select value={filter.quarter} onChange={e => setFilter(f => ({ ...f, quarter: e.target.value }))} className="select text-xs py-1.5">
                <option value="all">כל הרבעונים</option>
                {quarters.map(q => <option key={q} value={q}>{q}</option>)}
              </select>
            </div>
            <div>
              <label className="text-[10px] font-semibold text-slate-500 uppercase">אשכול</label>
              <select value={filter.cluster} onChange={e => setFilter(f => ({ ...f, cluster: e.target.value }))} className="select text-xs py-1.5">
                <option value="all">כל האשכולות</option>
                {window.ACTIVITY_BASKET.clusters.map(c => <option key={c.id} value={c.id}>{c.shortName}</option>)}
              </select>
            </div>
          </div>
        </div>
      </div>

      {/* Advanced filters — collapsible */}
      <div className="surface mb-5 overflow-hidden">
        <button onClick={() => setShowAdvanced(!showAdvanced)} className="w-full p-4 flex items-center justify-between hover:bg-slate-50 transition-colors">
          <div className="flex items-center gap-2">
            <window.Icon.Filter size={16} className="text-brand-600"/>
            <span className="font-display font-bold text-sm">סינונים מתקדמים</span>
            {activeFilterCount > 0 && (
              <span className="bg-brand-600 text-white text-[10px] font-bold rounded-full px-2 py-0.5">{activeFilterCount} פעילים</span>
            )}
          </div>
          <div className="flex items-center gap-2">
            {activeFilterCount > 0 && (
              <button onClick={(e) => { e.stopPropagation(); setFilter({ quarter: 'all', cluster: 'all', status: 'all', authorities: [], suppliers: [], gender: 'all', communityStream: 'all', dateFrom: '', dateTo: '', budgetMin: '', budgetMax: '' }); }}
                className="text-xs text-red-600 hover:underline">ניקוי סינונים</button>
            )}
            <window.Icon.ChevronDown size={16} className={`text-slate-400 transition-transform ${showAdvanced ? 'rotate-180' : ''}`}/>
          </div>
        </button>
        {showAdvanced && (
          <div className="p-4 pt-0 space-y-4 animate-fade-in">
            {/* Authorities */}
            <div>
              <label className="text-[10px] font-semibold text-slate-500 uppercase mb-2 block flex items-center gap-1.5">
                <window.Icon.Building size={11}/> רשויות
              </label>
              <div className="flex flex-wrap gap-1.5">
                {state.authorities.map(a => {
                  const on = (filter.authorities || []).includes(a.id);
                  return (
                    <button key={a.id} onClick={() => setFilter(f => ({
                      ...f, authorities: on ? (f.authorities || []).filter(x => x !== a.id) : [...(f.authorities || []), a.id]
                    }))} className="px-2.5 py-1 rounded-full text-xs font-semibold transition-all"
                      style={on ? { background: a.color, color: 'white' } : { background: a.color + '15', color: a.color, border: `1px solid ${a.color}33` }}>
                      {a.shortName || a.name}
                    </button>
                  );
                })}
              </div>
            </div>

            {/* Suppliers */}
            {suppliers.length > 0 && (
              <div>
                <label className="text-[10px] font-semibold text-slate-500 uppercase mb-2 block flex items-center gap-1.5">
                  <window.Icon.Briefcase size={11}/> ספקים
                </label>
                <div className="flex flex-wrap gap-1.5">
                  {suppliers.map(s => {
                    const on = (filter.suppliers || []).includes(s);
                    return (
                      <button key={s} onClick={() => setFilter(f => ({
                        ...f, suppliers: on ? (f.suppliers || []).filter(x => x !== s) : [...(f.suppliers || []), s]
                      }))} className={`px-2.5 py-1 rounded-full text-xs font-semibold transition-all ${on ? 'bg-emerald-600 text-white' : 'bg-emerald-50 text-emerald-700 border border-emerald-200 hover:bg-emerald-100'}`}>
                        {s}
                      </button>
                    );
                  })}
                </div>
              </div>
            )}

            {/* Status */}
            <div>
              <label className="text-[10px] font-semibold text-slate-500 uppercase mb-2 block flex items-center gap-1.5">
                <window.Icon.Activity size={11}/> סטטוס
              </label>
              <div className="flex flex-wrap gap-1.5">
                <button onClick={() => setFilter(f => ({ ...f, status: 'all' }))}
                  className={`px-2.5 py-1 rounded-full text-xs font-semibold ${filter.status === 'all' ? 'bg-brand-600 text-white' : 'bg-slate-100 text-slate-600 hover:bg-slate-200'}`}>הכל</button>
                {Object.entries(window.STATUS_META).map(([k, v]) => (
                  <button key={k} onClick={() => setFilter(f => ({ ...f, status: k }))}
                    className={`px-2.5 py-1 rounded-full text-xs font-semibold transition-all ${filter.status === k ? v.dot.replace('bg-', 'bg-') + ' text-white' : v.bg + ' ' + v.text + ' hover:opacity-80'}`}
                    style={filter.status === k ? { background: `var(--tw-${v.color})`, color: 'white' } : {}}>
                    {v.label}
                  </button>
                ))}
              </div>
            </div>

            {/* Dates + budget */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
              <div>
                <label className="text-[10px] font-semibold text-slate-500 uppercase flex items-center gap-1.5 mb-1">
                  <window.Icon.Calendar size={11}/> מתאריך
                </label>
                <input type="date" value={filter.dateFrom || ''} onChange={e => setFilter(f => ({ ...f, dateFrom: e.target.value }))} className="input text-xs py-1.5"/>
              </div>
              <div>
                <label className="text-[10px] font-semibold text-slate-500 uppercase flex items-center gap-1.5 mb-1">
                  <window.Icon.Calendar size={11}/> עד תאריך
                </label>
                <input type="date" value={filter.dateTo || ''} onChange={e => setFilter(f => ({ ...f, dateTo: e.target.value }))} className="input text-xs py-1.5"/>
              </div>
              <div>
                <label className="text-[10px] font-semibold text-slate-500 uppercase flex items-center gap-1.5 mb-1">
                  <window.Icon.Coins size={11}/> תקציב מינימום
                </label>
                <input type="number" value={filter.budgetMin || ''} onChange={e => setFilter(f => ({ ...f, budgetMin: e.target.value }))} className="input text-xs py-1.5 ltr-num" placeholder="₪"/>
              </div>
              <div>
                <label className="text-[10px] font-semibold text-slate-500 uppercase flex items-center gap-1.5 mb-1">
                  <window.Icon.Coins size={11}/> תקציב מקסימום
                </label>
                <input type="number" value={filter.budgetMax || ''} onChange={e => setFilter(f => ({ ...f, budgetMax: e.target.value }))} className="input text-xs py-1.5 ltr-num" placeholder="₪"/>
              </div>
            </div>

            {/* Gender + Community stream + Age group */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
              <div>
                <label className="text-[10px] font-semibold text-slate-500 uppercase flex items-center gap-1.5 mb-2">
                  <window.Icon.Users size={11}/> מגדר
                </label>
                <div className="flex gap-1.5 flex-wrap">
                  <button onClick={() => setFilter(f => ({ ...f, gender: 'all' }))}
                    className={`flex-1 px-2.5 py-1 rounded-full text-xs font-semibold ${!filter.gender || filter.gender === 'all' ? 'bg-brand-600 text-white' : 'bg-slate-100 text-slate-600 hover:bg-slate-200'}`}>הכל</button>
                  {window.GENDERS.map(g => (
                    <button key={g} onClick={() => setFilter(f => ({ ...f, gender: g }))}
                      className={`flex-1 px-2.5 py-1 rounded-full text-xs font-semibold ${filter.gender === g ? 'bg-brand-600 text-white' : 'bg-slate-100 text-slate-600 hover:bg-slate-200'}`}>{g}</button>
                  ))}
                </div>
              </div>
              <div>
                <label className="text-[10px] font-semibold text-slate-500 uppercase flex items-center gap-1.5 mb-2">
                  <window.Icon.Heart size={11}/> זרם קהילתי
                </label>
                <select value={filter.communityStream || 'all'} onChange={e => setFilter(f => ({ ...f, communityStream: e.target.value }))} className="select text-xs py-1.5">
                  <option value="all">כל הזרמים</option>
                  {window.COMMUNITY_STREAMS.map(s => <option key={s} value={s}>{s}</option>)}
                </select>
              </div>
              <div>
                <label className="text-[10px] font-semibold text-slate-500 uppercase flex items-center gap-1.5 mb-2">
                  <window.Icon.Users size={11}/> קבוצת גיל
                </label>
                <select value={filter.ageGroup || 'all'} onChange={e => setFilter(f => ({ ...f, ageGroup: e.target.value }))} className="select text-xs py-1.5">
                  <option value="all">כל הגילים</option>
                  <option value="0-5">גיל הרך (0-5)</option>
                  <option value="6-13">יסודי (6-13)</option>
                  <option value="14-18">נוער (14-18)</option>
                  <option value="18-30">צעירים (18-30)</option>
                  <option value="30+">מבוגרים (30+)</option>
                  <option value="הורים">הורים</option>
                  <option value="ותיקים">אזרחים ותיקים</option>
                </select>
              </div>
            </div>
          </div>
        )}
      </div>

      {/* Result header */}
      <div className="surface p-5 mb-4 flex items-center justify-between flex-wrap gap-3">
        <div>
          <h3 className="font-display font-bold text-lg">
            {currentMeasure?.label} · {dimensions.find(d => d.id === dimension)?.label}
          </h3>
          <div className="text-sm text-slate-500">
            {activities.length} פעילויות בניתוח · {groupedData.length} קבוצות
          </div>
        </div>
        <div className="p-3 rounded-xl bg-gradient-to-br from-brand-50 to-indigo-50 border border-brand-100">
          <div className="text-[10px] text-brand-700 font-semibold">סה"כ {currentMeasure?.label}</div>
          <div className="font-display font-black text-2xl text-brand-900 ltr-num">
            {currentMeasure?.unit}{' '}
            {currentMeasure?.unit === '₪' ? window.formatMoney(totalValue).replace('₪ ', '') : totalValue.toLocaleString('he-IL')}
          </div>
        </div>
      </div>

      {/* Chart */}
      <div className="surface p-5">
        {groupedData.length === 0 ? (
          <window.EmptyState icon="BarChart" title="אין נתונים" description="שנה את המסננים או בחר דימנסיה אחרת"/>
        ) : chartType === 'bar' ? (
          <R.ResponsiveContainer width="100%" height={400}>
            <R.BarChart data={groupedData} margin={{ top: 10, right: 20, left: 20, bottom: 10 }}>
              <R.CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0"/>
              <R.XAxis dataKey="name" tick={{ fontSize: 11, fill: '#64748b' }}/>
              <R.YAxis tick={{ fontSize: 11, fill: '#64748b' }} tickFormatter={v => currentMeasure?.unit === '₪' ? (v >= 1000 ? (v/1000).toFixed(0) + 'K' : v) : v}/>
              <R.Tooltip formatter={v => currentMeasure?.unit === '₪' ? `₪ ${v.toLocaleString('he-IL')}` : v.toLocaleString('he-IL')}
                contentStyle={{ borderRadius: 10, border: '1px solid #e2e8f0', fontSize: 12 }}/>
              <R.Bar dataKey="value" radius={[6, 6, 0, 0]}>
                {groupedData.map((g, i) => <R.Cell key={i} fill={g.color || chartColors[i % chartColors.length]}/>)}
              </R.Bar>
            </R.BarChart>
          </R.ResponsiveContainer>
        ) : chartType === 'pie' ? (
          <R.ResponsiveContainer width="100%" height={400}>
            <R.PieChart>
              <R.Pie data={groupedData} dataKey="value" nameKey="name" outerRadius={140} innerRadius={70} paddingAngle={2} label={(entry) => entry.name}>
                {groupedData.map((g, i) => <R.Cell key={i} fill={g.color || chartColors[i % chartColors.length]}/>)}
              </R.Pie>
              <R.Tooltip formatter={v => currentMeasure?.unit === '₪' ? `₪ ${v.toLocaleString('he-IL')}` : v.toLocaleString('he-IL')}
                contentStyle={{ borderRadius: 10, border: '1px solid #e2e8f0', fontSize: 12 }}/>
              <R.Legend wrapperStyle={{ fontSize: 12 }}/>
            </R.PieChart>
          </R.ResponsiveContainer>
        ) : chartType === 'line' ? (
          <R.ResponsiveContainer width="100%" height={400}>
            <R.LineChart data={groupedData}>
              <R.CartesianGrid strokeDasharray="3 3" stroke="#e2e8f0"/>
              <R.XAxis dataKey="name" tick={{ fontSize: 11, fill: '#64748b' }}/>
              <R.YAxis tick={{ fontSize: 11, fill: '#64748b' }} tickFormatter={v => currentMeasure?.unit === '₪' ? (v >= 1000 ? (v/1000).toFixed(0) + 'K' : v) : v}/>
              <R.Tooltip formatter={v => currentMeasure?.unit === '₪' ? `₪ ${v.toLocaleString('he-IL')}` : v.toLocaleString('he-IL')}
                contentStyle={{ borderRadius: 10, border: '1px solid #e2e8f0', fontSize: 12 }}/>
              <R.Line type="monotone" dataKey="value" stroke="#2563eb" strokeWidth={3} dot={{ r: 5, fill: '#2563eb' }}/>
            </R.LineChart>
          </R.ResponsiveContainer>
        ) : (
          <div className="overflow-x-auto">
            <table className="data-table">
              <thead>
                <tr>
                  <th>#</th>
                  <th>קבוצה</th>
                  <th>ערך</th>
                  <th>% מהסך</th>
                  <th>בר</th>
                </tr>
              </thead>
              <tbody>
                {groupedData.map((g, i) => {
                  const pct = totalValue ? (g.value / totalValue * 100) : 0;
                  return (
                    <tr key={g.key}>
                      <td className="font-mono text-sm">{i + 1}</td>
                      <td>
                        <div className="flex items-center gap-2">
                          <div className="w-3 h-3 rounded-full" style={{ background: g.color || chartColors[i % chartColors.length] }}/>
                          <span className="font-semibold">{g.name}</span>
                        </div>
                      </td>
                      <td className="font-bold ltr-num">
                        {currentMeasure?.unit === '₪' ? window.formatMoney(g.value) : g.value.toLocaleString('he-IL')}
                      </td>
                      <td className="text-sm">{pct.toFixed(1)}%</td>
                      <td style={{ width: 200 }}>
                        <div className="h-2 bg-slate-100 rounded-full overflow-hidden">
                          <div className="h-full rounded-full" style={{ width: `${pct}%`, background: g.color || chartColors[i % chartColors.length] }}/>
                        </div>
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>

      {/* Saved presets (future) */}
      <div className="mt-5 surface p-4 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.Lightbulb size={18}/>
          </div>
          <div>
            <div className="font-display font-bold text-sm text-amber-900">טיפ</div>
            <div className="text-xs text-amber-800 mt-0.5">
              בחר פיצול + מדד + תצוגה כדי לנתח את הנתונים בכל דרך. ניתן לסנן לפי רבעון ואשכול. הנתון יוצא ל-CSV להעברה מהירה לאקסל.
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};
