/* global React, Icon, Card, Pill, Avatar, Money, Balance, Overline, CountUp */
// Schools.ArtemenkoCRM — Dashboard

function StatCard({ overline, value, delta, deltaKind, foot, footValue, delay }) {
  const deltaColor = deltaKind === 'down' ? 'var(--coral)' : 'var(--green)';
  return (
    <Card pad={22} className="om-card-in" style={{ animationDelay: (delay || 0) + 'ms' }}>
      <div style={{ minHeight: 30 }}><Overline>{overline}</Overline></div>
      <div style={{ fontSize: 28, fontWeight: 700, letterSpacing: '-0.5px', color: 'var(--text)', margin: '12px 0 6px', fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' }}>{value}</div>
      {delta && (
        <div style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 13, fontWeight: 600, color: deltaColor, whiteSpace: 'nowrap' }}>
          <Icon name={deltaKind === 'down' ? 'arrow-down' : 'arrow-up'} size={14} strokeWidth={2.5} />{delta}
        </div>
      )}
      {foot && (
        <div style={{ marginTop: 16, paddingTop: 14, borderTop: '1px solid var(--border)', fontSize: 13, color: 'var(--text-dim)', display: 'flex', justifyContent: 'space-between', gap: 8, whiteSpace: 'nowrap' }}>
          <span>{foot}</span>{footValue}
        </div>
      )}
    </Card>
  );
}

function RevenueChart({ delay }) {
  const data = [62, 48, 71, 58, 80, 66, 91, 74, 88, 79, 102, 124];
  const months = ['И','Ф','М','А','М','И','И','А','С','О','Н','Д'];
  const max = Math.max(...data);
  return (
    <Card pad={24} className="om-card-in" style={{ gridColumn: 'span 2', animationDelay: (delay || 0) + 'ms' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 4 }}>
        <Overline>Выручка по месяцам</Overline>
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-dim)' }}>2026, тыс. ₽</span>
      </div>
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 10, height: 140, marginTop: 20 }}>
        {data.map((v, i) => (
          <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
            {/* столбец вырастает снизу из нуля, с каскадом по месяцам */}
            <div className="om-grow-up" style={{
              width: '100%', height: (v / max) * 120, borderRadius: '4px 4px 0 0',
              background: i === data.length - 1 ? 'var(--brand)' : 'var(--brand-soft)',
              animationDelay: ((delay || 0) + 120 + i * 42) + 'ms',
            }} />
            <span style={{ fontSize: 11, color: 'var(--text-dim)', fontWeight: 600 }}>{months[i]}</span>
          </div>
        ))}
      </div>
    </Card>
  );
}

function ActivityFeed({ onOpenClients, delay }) {
  const { CLIENTS } = window.CRM_DATA;
  const recent = CLIENTS.slice(0, 6);
  return (
    <Card pad={0} className="om-card-in" style={{ gridColumn: 'span 2', overflow: 'hidden', animationDelay: (delay || 0) + 'ms' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '20px 24px 16px' }}>
        <Overline>Недавние клиенты</Overline>
        <button onClick={onOpenClients} style={{ border: 'none', background: 'none', cursor: 'pointer', color: 'var(--brand-ink)', fontSize: 13, fontWeight: 600, display: 'inline-flex', alignItems: 'center', gap: 3 }}>
          Все клиенты <Icon name="chevron-right" size={15} />
        </button>
      </div>
      <div>
        {recent.map((c, i) => (
          <div key={c.id} className="om-row-in row-hover" style={{
            display: 'flex', alignItems: 'center', gap: 12, padding: '12px 24px',
            borderTop: '1px solid var(--border)', animationDelay: ((delay || 0) + 120 + i * 45) + 'ms',
          }}>
            <Avatar animal={c.animal} tone={c.tone} size={36} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)' }}>{c.child}</div>
              <div style={{ fontSize: 12.5, color: 'var(--text-dim)' }}>{c.source} · {c.date}</div>
            </div>
            <div style={{ width: 90, textAlign: 'right' }}><Balance value={c.balance} /></div>
            <div style={{ width: 120, display: 'flex', justifyContent: 'flex-end' }}><Pill kind={c.status} /></div>
          </div>
        ))}
      </div>
    </Card>
  );
}

function Dashboard({ onOpenPayments, onOpenClients }) {
  const { CLIENTS, LEADS } = window.CRM_DATA;
  const active = CLIENTS.filter(c => c.status === 'active').length;
  const inFunnel = CLIENTS.filter(c => ['new','call','trial','payment'].includes(c.status)).length;
  const onBalance = CLIENTS.reduce((a, c) => a + (c.balance > 0 ? c.balance : 0), 0);
  const nf = (v) => new Intl.NumberFormat('ru-RU').format(v);
  return (
    <div style={{ padding: 32, display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 20 }}>
      <StatCard delay={0} overline="Активные клиенты" value={<CountUp to={active} />} delta="+3 за неделю" deltaKind="up" foot="Всего в базе" footValue={<span style={{ fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--text-secondary)', fontWeight: 600 }}>{CLIENTS.length}</span>} />
      <StatCard delay={60} overline="В воронке" value={<CountUp to={inFunnel} />} delta="новые + созвон + пробное" deltaKind="up" foot="Новых заявок" footValue={<span style={{ fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--brand-ink)', fontWeight: 600 }}>{LEADS.length}</span>} />
      <StatCard delay={120} overline="Средства на балансах" value={<CountUp to={onBalance} format={(v) => nf(v) + ' ₽'} />} delta="по активным клиентам" deltaKind="up" foot="Занятие" footValue={<span style={{ fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--text-secondary)', fontWeight: 600 }}>1 800 ₽</span>} />
      <StatCard delay={180} overline="Конверсия заявок" value={<CountUp to={100} format={(v) => v + '%'} />} delta="5 из 5 за апрель" deltaKind="up" foot="Отказов" footValue={<span style={{ fontSize: 13, color: 'var(--coral)', fontWeight: 600 }}>{CLIENTS.filter(c=>c.status==='refusal').length}</span>} />
      <RevenueChart delay={240} />
      <ActivityFeed onOpenClients={onOpenClients} delay={300} />
    </div>
  );
}

Object.assign(window, { Dashboard });
