// Savings Recommendations page — Cai-curated, actionable

function SavingsPage() {
  const [filter, setFilter] = useState('all'); // all | easy | high
  const [accepted, setAccepted] = useState({});
  const [dismissed, setDismissed] = useState({});
  const [expanded, setExpanded] = useState(null);
  const [busy, setBusy] = useState(false);

  const savings = D.savings || {};
  const allItems = savings.items || [];
  const aiConfigured = D.aiStatus?.configured;
  const hasReport = allItems.length > 0;

  const items = useMemo(() => {
    let arr = allItems.filter(i => !dismissed[i.id]);
    if (filter === 'easy') arr = arr.filter(i => i.effort === 'easy');
    if (filter === 'high') arr = arr.filter(i => i.impact === 'high');
    if (filter === 'subs') arr = arr.filter(i => i.category === 'חשבונות ומנויים');
    // sort by impact * confidence desc
    const score = (i) => (i.annual || 0) * (i.confidence || 0.5) * (i.effort === 'easy' ? 1.2 : i.effort === 'medium' ? 1 : 0.8);
    return arr.sort((a, b) => score(b) - score(a));
  }, [filter, dismissed, hasReport]);

  const acceptedItems = allItems.filter(i => accepted[i.id]);
  const acceptedAnnual = acceptedItems.reduce((s, i) => s + (i.annual || 0), 0);
  const acceptedMonthly = acceptedItems.reduce((s, i) => s + (i.monthly || 0), 0);

  const totalAvailableAnnual = items.reduce((s, i) => s + (i.annual || 0), 0);

  const generate = async () => {
    if (!aiConfigured) {
      alert('AI לא מוגדר. הגדר ANTHROPIC_API_KEY ב-environment והפעל את השרת מחדש.');
      return;
    }
    if (busy) return;
    if (hasReport && !confirm('הניתוח הקיים יוחלף בניתוח חדש (יקח כדקה). להמשיך?')) return;
    setBusy(true);
    try {
      const r = await apiFetch('/api/ai/savings', { method: 'POST' });
      if (!r.ok) {
        const err = await r.json().catch(() => ({}));
        throw new Error(err.detail?.message || 'הניתוח נכשל');
      }
      await window.APP_DATA_REFRESH();
    } catch (err) {
      alert('שגיאה בניתוח: ' + err.message);
    } finally {
      setBusy(false);
    }
  };

  const updatedLabel = savings.createdAt
    ? new Date(savings.createdAt).toLocaleString('he-IL', { dateStyle: 'short', timeStyle: 'short' })
    : null;
  const modelLabel = savings.model || D.aiStatus?.model || 'Cai';

  return (
    <div className="fade-in" style={{ padding: '32px 40px 60px', maxWidth: 1100, margin: '0 auto' }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 6 }}>
        <SparkBadge size={36} />
        <div style={{ flex: 1 }}>
          <h1 style={{ fontSize: 26, fontWeight: 600, letterSpacing: '-0.02em', margin: 0 }}>איפה אפשר לחסוך</h1>
          <div style={{ fontSize: 12, color: 'var(--ink-soft)', marginTop: 2 }}>
            המלצות מבוססות נתונים · 12 חודשים אחרונים · {updatedLabel ? `עודכן ${updatedLabel}` : 'לא נוצר עדיין'} · {modelLabel}
          </div>
        </div>
        <button
          onClick={generate}
          disabled={busy || !aiConfigured}
          style={{
            background: 'var(--surface)', color: 'var(--ink)',
            border: '0.5px solid var(--rule)', padding: '8px 14px',
            borderRadius: 10, fontSize: 12.5,
            cursor: busy ? 'wait' : (aiConfigured ? 'pointer' : 'not-allowed'),
            boxShadow: 'var(--shadow-sm)',
            opacity: !aiConfigured ? 0.5 : (busy ? 0.7 : 1),
          }}>
          {busy ? '⟳ Cai מנתח…' : (hasReport ? '↻ נתח שוב' : '✦ נתח עכשיו')}
        </button>
      </div>

      {/* Hero — total potential */}
      <Surface style={{ marginTop: 22, marginBottom: 16, padding: 0, overflow: 'hidden' }} padded={false}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr 1fr' }}>
          <div style={{ padding: '26px 30px', borderInlineEnd: '0.5px solid var(--rule)' }}>
            <div style={{ fontSize: 11.5, color: 'var(--ink-soft)', fontWeight: 500, letterSpacing: '0.02em', marginBottom: 6 }}>פוטנציאל חיסכון שנתי</div>
            <Money value={(savings.annualPotential || 0)} size={44} weight={700} />
            <div style={{ fontSize: 12.5, color: 'var(--ink-2)', marginTop: 6, lineHeight: 1.55, maxWidth: 380 }}>
              {savings.summary}
            </div>
          </div>
          <SavingsHeroStat
            label="חיסכון חודשי משוער"
            value={(savings.monthlyPotential || 0)}
            sub={`${allItems.length} הזדמנויות זוהו`}
          />
          <SavingsHeroStat
            label="ניצחונות מהירים"
            value={(savings.quickWinAnnual || 0)}
            sub="ללא שינוי באורח החיים"
            accent
          />
        </div>

        {/* Accepted progress bar */}
        {acceptedItems.length > 0 && (
          <div style={{
            padding: '14px 30px', background: 'var(--bg-deep)', borderTop: '0.5px solid var(--rule)',
            display: 'flex', alignItems: 'center', gap: 14,
          }}>
            <div style={{
              width: 28, height: 28, borderRadius: 8, background: 'var(--positive)', color: 'white',
              display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 14, fontWeight: 700,
            }}>✓</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 12.5, fontWeight: 600 }}>
                סימנת {acceptedItems.length} מתוך {allItems.length} המלצות לביצוע
              </div>
              <div style={{ fontSize: 11, color: 'var(--ink-soft)', marginTop: 2 }}>
                חיסכון מצטבר: <span className="tnum" style={{ fontWeight: 600, color: 'var(--positive)' }}>{fmtILS(acceptedMonthly)}/חודש</span> · {fmtILS(acceptedAnnual)} בשנה
              </div>
            </div>
            <div style={{ width: 140, height: 6, background: 'var(--surface)', borderRadius: 99, overflow: 'hidden' }}>
              <div style={{
                width: `${Math.min(100, (acceptedAnnual / (savings.annualPotential || 0)) * 100)}%`,
                height: '100%', background: 'var(--positive)', borderRadius: 99, transition: 'width .5s',
              }} />
            </div>
          </div>
        )}
      </Surface>

      {/* Filter chips */}
      <div style={{ display: 'flex', gap: 8, marginBottom: 14, alignItems: 'center', flexWrap: 'wrap' }}>
        <FilterChip label={`הכל · ${allItems.length}`} on={filter==='all'} onClick={()=>setFilter('all')} />
        <FilterChip label="קל לבצע" on={filter==='easy'} onClick={()=>setFilter('easy')} icon="⚡" />
        <FilterChip label="חיסכון גבוה" on={filter==='high'} onClick={()=>setFilter('high')} icon="↑" />
        <FilterChip label="מנויים" on={filter==='subs'} onClick={()=>setFilter('subs')} />
        <span style={{ flex: 1 }} />
        <span style={{ fontSize: 11, color: 'var(--ink-soft)' }}>
          מציג {items.length} · סך פוטנציאל <span className="tnum" style={{ fontWeight: 600, color: 'var(--ink)' }}>{fmtILS(totalAvailableAnnual)}/שנה</span>
        </span>
      </div>

      {/* Recommendations list */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {items.map((it, i) => (
          <SavingItem
            key={it.id}
            item={it}
            rank={i+1}
            isAccepted={!!accepted[it.id]}
            isExpanded={expanded === it.id}
            onToggle={() => setExpanded(expanded === it.id ? null : it.id)}
            onAccept={() => setAccepted(a => ({ ...a, [it.id]: !a[it.id] }))}
            onDismiss={() => setDismissed(d => ({ ...d, [it.id]: true }))}
          />
        ))}
        {items.length === 0 && (
          <Surface><EmptyState icon="✓" title="ניצחת את הפילטר" sub="אין המלצות מתאימות לסינון הנוכחי. נסה פילטר אחר." /></Surface>
        )}
      </div>

      {/* Footer note */}
      <div style={{
        marginTop: 22, padding: 16, background: 'var(--bg-deep)', borderRadius: 12,
        fontSize: 11.5, color: 'var(--ink-soft)', lineHeight: 1.55,
      }}>
        <span style={{ fontWeight: 600, color: 'var(--ink-2)' }}>איך החישוב נעשה:</span>{' '}
        ההמלצות מבוססות על ניתוח של 12 חודשים אחרונים, הצלבה עם תעריפי שוק, ודפוסי שימוש שזוהו אוטומטית. רמת הביטחון משקפת את איכות הנתונים — לא הבטחה. אתה תמיד שומר על שליטה: שום פעולה לא מתבצעת אוטומטית.
      </div>
    </div>
  );
}

function SavingsHeroStat({ label, value, sub, accent }) {
  return (
    <div style={{
      padding: '26px 28px', borderInlineEnd: '0.5px solid var(--rule)',
      display: 'flex', flexDirection: 'column', justifyContent: 'center',
      background: accent ? 'var(--bg-deep)' : 'transparent',
    }}>
      <div style={{ fontSize: 11.5, color: 'var(--ink-soft)', fontWeight: 500, letterSpacing: '0.02em', marginBottom: 6 }}>{label}</div>
      <Money value={value} size={26} weight={600} color={accent ? 'var(--accent)' : undefined} />
      <div style={{ fontSize: 11, color: 'var(--ink-soft)', marginTop: 6 }}>{sub}</div>
    </div>
  );
}

function FilterChip({ label, on, onClick, icon }) {
  return (
    <button onClick={onClick} style={{
      padding: '6px 12px', borderRadius: 99,
      background: on ? 'var(--ink)' : 'var(--surface)',
      color: on ? 'var(--bg)' : 'var(--ink-2)',
      border: on ? 'none' : '0.5px solid var(--rule)',
      fontSize: 12, fontWeight: 500, cursor: 'pointer',
      boxShadow: on ? 'none' : 'var(--shadow-sm)',
      display: 'inline-flex', alignItems: 'center', gap: 5,
    }}>
      {icon && <span>{icon}</span>}{label}
    </button>
  );
}

function SavingItem({ item, rank, isAccepted, isExpanded, onToggle, onAccept, onDismiss }) {
  const cat = D.categories[item.category] || { color: 'var(--ink-soft)', icon: '·' };
  const effortLabel = { easy: 'קל', medium: 'בינוני', hard: 'מורכב' }[item.effort];
  const impactLabel = { low: 'נמוך', medium: 'בינוני', high: 'גבוה' }[item.impact];
  const impactColor = { low: 'var(--ink-soft)', medium: 'var(--accent)', high: 'var(--positive)' }[item.impact];

  return (
    <Surface
      padded={false}
      className="slide-up"
      style={{
        animationDelay: `${rank * 30}ms`,
        opacity: isAccepted ? 0.7 : 1,
        transition: 'opacity .2s',
      }}
    >
      <div onClick={onToggle} style={{
        padding: '18px 22px', display: 'flex', gap: 16, alignItems: 'flex-start', cursor: 'pointer',
      }}>
        {/* Rank + category icon */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, paddingTop: 2 }}>
          <div className="tnum" style={{
            fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--ink-soft)', fontWeight: 600,
          }}>#{rank}</div>
          <div style={{
            width: 38, height: 38, borderRadius: 10, background: `${cat.color}22`,
            display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 16,
          }}>{cat.icon}</div>
        </div>

        {/* Body */}
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 3, flexWrap: 'wrap' }}>
            <span style={{
              fontSize: 14.5, fontWeight: 600, letterSpacing: '-0.01em',
              textDecoration: isAccepted ? 'line-through' : 'none',
              textDecorationColor: 'var(--ink-faint)',
              textDecorationThickness: '1px',
            }}>{item.title}</span>
            {isAccepted && <Pill color="var(--positive)" label="✓ סומן לביצוע" />}
          </div>
          <div style={{ fontSize: 12, color: 'var(--ink-soft)', marginBottom: 10 }}>
            {item.category} · {item.sub}
          </div>

          {/* Meta strip */}
          <div style={{ display: 'flex', gap: 14, alignItems: 'center', flexWrap: 'wrap' }}>
            <Meta label="חיסכון חודשי" value={fmtILS(item.monthly)} accent="var(--positive)" />
            <MetaDivider />
            <Meta label="מאמץ" value={effortLabel} dot={item.effort === 'easy' ? 'var(--positive)' : item.effort === 'hard' ? 'var(--alert)' : 'var(--warn)'} />
            <Meta label="השפעה" value={impactLabel} dot={impactColor} />
            <MetaDivider />
            <ConfidenceBar value={item.confidence} />
          </div>
        </div>

        {/* Annual savings */}
        <div style={{ textAlign: 'left', flexShrink: 0, paddingTop: 4 }}>
          <div style={{ fontSize: 10.5, color: 'var(--ink-soft)', marginBottom: 2, letterSpacing: '0.02em' }}>בשנה</div>
          <div className="tnum" style={{ fontSize: 22, fontWeight: 700, letterSpacing: '-0.02em', color: 'var(--positive)' }}>
            {fmtILS(item.annual)}
          </div>
          <div style={{ fontSize: 10.5, color: 'var(--ink-soft)', marginTop: 2, fontFamily: 'var(--font-mono)' }}>
            {isExpanded ? '⌃ סגור' : '⌄ הרחב'}
          </div>
        </div>
      </div>

      {/* Expanded detail */}
      {isExpanded && (
        <div className="fade-in" style={{
          padding: '18px 22px 20px 22px', borderTop: '0.5px solid var(--rule)',
          background: 'var(--bg-deep)',
          marginInlineStart: 76 - 22, // align with body, not icon column
        }}>
          {/* Why */}
          <div style={{ marginBottom: 14 }}>
            <div style={{ fontSize: 10.5, fontWeight: 600, color: 'var(--ink-soft)', letterSpacing: '0.04em', textTransform: 'uppercase', marginBottom: 6 }}>למה זה אפשרי</div>
            <div style={{ fontSize: 13, lineHeight: 1.6, color: 'var(--ink-2)' }}>{item.why}</div>
          </div>

          {/* Evidence */}
          {item.evidence && (
            <div style={{ marginBottom: 16 }}>
              <div style={{ fontSize: 10.5, fontWeight: 600, color: 'var(--ink-soft)', letterSpacing: '0.04em', textTransform: 'uppercase', marginBottom: 6 }}>ראיות</div>
              <ul style={{ margin: 0, paddingInlineStart: 18, fontSize: 12.5, lineHeight: 1.7, color: 'var(--ink-2)' }}>
                {item.evidence.map((e, i) => <li key={i}>{e}</li>)}
              </ul>
            </div>
          )}

          {/* Actions */}
          <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexWrap: 'wrap' }}>
            <button
              onClick={(e) => { e.stopPropagation(); onAccept(); }}
              style={{
                padding: '9px 16px', borderRadius: 9,
                background: isAccepted ? 'var(--surface)' : 'var(--ink)',
                color: isAccepted ? 'var(--ink)' : 'var(--bg)',
                border: isAccepted ? '0.5px solid var(--rule)' : 'none',
                fontSize: 12.5, fontWeight: 600, cursor: 'pointer',
                display: 'inline-flex', alignItems: 'center', gap: 6,
              }}>
              {isAccepted ? '↩ בטל סימון' : `✓ ${item.action}`}
            </button>
            <button style={{
              padding: '9px 14px', borderRadius: 9, background: 'var(--surface)',
              border: '0.5px solid var(--rule)', fontSize: 12.5, cursor: 'pointer',
            }}>הזכר לי בעוד שבוע</button>
            <button
              onClick={(e) => { e.stopPropagation(); onDismiss(); }}
              style={{
                padding: '9px 14px', borderRadius: 9, background: 'transparent',
                border: 'none', fontSize: 12, cursor: 'pointer', color: 'var(--ink-soft)',
                marginInlineStart: 'auto',
              }}>לא רלוונטי</button>
          </div>
        </div>
      )}
    </Surface>
  );
}

function Meta({ label, value, accent, dot }) {
  return (
    <div style={{ display: 'inline-flex', flexDirection: 'column', gap: 2 }}>
      <span style={{ fontSize: 10, color: 'var(--ink-soft)', letterSpacing: '0.02em' }}>{label}</span>
      <span className="tnum" style={{ fontSize: 12.5, fontWeight: 600, color: accent || 'var(--ink)', display: 'inline-flex', alignItems: 'center', gap: 5 }}>
        {dot && <span style={{ width: 6, height: 6, borderRadius: '50%', background: dot, display: 'inline-block' }} />}
        {value}
      </span>
    </div>
  );
}

function MetaDivider() {
  return <span style={{ width: 1, height: 22, background: 'var(--rule)' }} />;
}

function ConfidenceBar({ value }) {
  const pct = Math.round(value * 100);
  return (
    <div style={{ display: 'inline-flex', flexDirection: 'column', gap: 4 }}>
      <span style={{ fontSize: 10, color: 'var(--ink-soft)', letterSpacing: '0.02em' }}>ביטחון</span>
      <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
        <div style={{ width: 50, height: 4, background: 'var(--bg-deep)', borderRadius: 99, overflow: 'hidden' }}>
          <div style={{ width: `${pct}%`, height: '100%', background: 'var(--ink)', borderRadius: 99 }} />
        </div>
        <span className="tnum" style={{ fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--ink-soft)', fontWeight: 500 }}>{pct}%</span>
      </div>
    </div>
  );
}

function Pill({ color, label }) {
  return (
    <span style={{
      fontSize: 10, fontWeight: 600, padding: '2px 7px', borderRadius: 4,
      background: `${color}22`, color, letterSpacing: '0.02em',
    }}>{label}</span>
  );
}

window.SavingsPage = SavingsPage;
