/* ============================================================
   admin-finance.jsx — P&L Финансы
   API: { revenue:{rub,starsRub,totalRub,subscriptionRub,diamondRub},
          costs:{totalRub,byProvider:{openai,gemini,fal}},
          profit:{rub,marginPct}, activity:{totalUsers,activeToday,activeWeek,totalGens,gensToday},
          modelStats:[], daily:[] }
   ============================================================ */

const { useState, useEffect } = React;

function AdminFinance() {
  const { API_BASE } = useAuth();
  const [period, setPeriod] = useState('7d');
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(false);

  async function load(p) {
    setLoading(true);
    try {
      const r = await fetch(`${API_BASE}/api/tg/admin/finance?period=${p}`, { credentials: 'include' });
      if (r.ok) setData(await r.json());
    } catch {}
    finally { setLoading(false); }
  }

  useEffect(() => { load(period); }, [period]);

  const PERIODS = [
    { value: '7d', label: '7 дней' },
    { value: '30d', label: '30 дней' },
    { value: '90d', label: '90 дней' },
    { value: 'alltime', label: 'Всё время' },
  ];

  function fmt(n) { return n != null ? Number(n).toLocaleString('ru') : '—'; }

  const rev = data?.revenue || {};
  const cost = data?.costs || {};
  const prof = data?.profit || {};
  const act = data?.activity || {};

  const mainStats = data ? [
    { label: 'Выручка', value: `${fmt(rev.totalRub)}₽`, icon: '💰', color: '#34d399' },
    { label: 'Расход (AI)', value: `${fmt(cost.totalRub)}₽`, icon: '🤖', color: '#fca5a5' },
    { label: 'Прибыль', value: `${fmt(prof.rub)}₽`, icon: '📈', color: (prof.rub ?? 0) >= 0 ? '#34d399' : '#fca5a5' },
    { label: 'Маржа', value: `${fmt(prof.marginPct)}%`, icon: '📊', color: '#c4b5fd' },
    { label: 'Всего юзеров', value: fmt(act.totalUsers), icon: '👥', color: '#7dd3fc' },
    { label: 'Всего генераций', value: fmt(act.totalGens), icon: '🎨', color: '#fde68a' },
  ] : [];

  const providerRows = cost.byProvider ? Object.entries(cost.byProvider) : [];
  const revenueRows = data ? [
    ['Алмазы (₽)', rev.diamondRub],
    ['Подписки (₽)', rev.subscriptionRub],
    ['Stars (₽-экв.)', rev.starsRub],
  ] : [];

  return (
    <div>
      <div className="page-head">
        <div className="page-head-text">
          <h1 className="page-title h-display">💰 Финансы</h1>
          <p className="page-sub muted">P&L по периодам</p>
        </div>
        <Seg items={PERIODS} value={period} onChange={v => { setPeriod(v); }} />
      </div>

      {loading && <div style={{ textAlign: 'center', padding: 40 }}><Spinner /></div>}

      {!loading && data && (
        <>
          <div className="grid-3" style={{ marginBottom: 28 }}>
            {mainStats.map(s => (
              <div key={s.label} className="glass" style={{ padding: '22px 24px' }}>
                <div style={{ fontSize: 24, marginBottom: 8 }}>{s.icon}</div>
                <div style={{ fontSize: 28, fontWeight: 800, color: s.color }}>{s.value}</div>
                <div className="muted" style={{ fontSize: 13, marginTop: 4 }}>{s.label}</div>
              </div>
            ))}
          </div>

          {/* Активность */}
          <div className="glass" style={{ padding: '0 6px', marginBottom: 20 }}>
            <div style={{ padding: '18px 18px 12px', fontWeight: 700, fontSize: 16 }}>Активность</div>
            <div className="vid-row"><span style={{ fontWeight: 600 }}>Активны сегодня</span><span style={{ color: '#7dd3fc', fontWeight: 700 }}>{fmt(act.activeToday)}</span></div>
            <div className="vid-row"><span style={{ fontWeight: 600 }}>Активны за неделю</span><span style={{ color: '#7dd3fc', fontWeight: 700 }}>{fmt(act.activeWeek)}</span></div>
            <div className="vid-row"><span style={{ fontWeight: 600 }}>Генераций сегодня</span><span style={{ color: '#fde68a', fontWeight: 700 }}>{fmt(act.gensToday)}</span></div>
          </div>

          {/* Выручка по типам */}
          <div className="glass" style={{ padding: '0 6px', marginBottom: 20 }}>
            <div style={{ padding: '18px 18px 12px', fontWeight: 700, fontSize: 16 }}>Выручка по типам</div>
            {revenueRows.map(([name, val]) => (
              <div key={name} className="vid-row">
                <span style={{ fontWeight: 600 }}>{name}</span>
                <span style={{ color: '#34d399', fontWeight: 700 }}>{fmt(val)}₽</span>
              </div>
            ))}
          </div>

          {/* Расход по провайдерам */}
          {providerRows.length > 0 && (
            <div className="glass" style={{ padding: '0 6px' }}>
              <div style={{ padding: '18px 18px 12px', fontWeight: 700, fontSize: 16 }}>Расход по провайдерам</div>
              {providerRows.map(([name, info]) => (
                <div key={name} className="vid-row">
                  <span style={{ fontWeight: 600 }}>{name}{info?.isReal ? ' ✓' : ''}</span>
                  <span style={{ color: '#fca5a5', fontWeight: 700 }}>{fmt(info?.rub)}₽</span>
                </div>
              ))}
            </div>
          )}

          {/* По моделям */}
          {data.modelStats && data.modelStats.length > 0 && (
            <div className="glass" style={{ padding: '0 6px', marginTop: 20 }}>
              <div style={{ padding: '18px 18px 12px', fontWeight: 700, fontSize: 16 }}>По моделям</div>
              {data.modelStats.map(m => (
                <div key={m.model} className="vid-row">
                  <span style={{ fontWeight: 600 }}>{m.title} <span className="muted">· {m.genCount} ген.</span></span>
                  <span style={{ color: '#fca5a5', fontWeight: 700 }}>{fmt(m.totalRub)}₽</span>
                </div>
              ))}
            </div>
          )}
        </>
      )}

      {!loading && !data && (
        <EmptyState icon="📊" title="Нет данных" sub="Попробуй другой период" />
      )}
    </div>
  );
}
